#!/usr/bin/env bash

SOURCE="${BASH_SOURCE[0]}"

# If the current source is a symbolic link, we need to resolve it to an
# actual directory name. We'll use PHP to do this easier than we can
# do it in pure Bash. So, we'll call into PHP CLI here to resolve.
if [[ -L "$SOURCE" ]]
then
    DIR=$(php -r "echo dirname(realpath('$SOURCE'));")
else
    DIR="$( cd "$( dirname "$SOURCE" )" && pwd )"
fi

# If we are in the global Composer "bin" directory, we need to bump our
# current directory up two, so that we will correctly proxy into the
# Valet CLI script which is written in PHP. Will use PHP to do it.
if [ ! -f "$DIR/src/index.php" ]
then
    DIR=$(php -r "echo realpath('$DIR/../micheld/charcoal-conductor');")
fi

# Get a command-line executable we can use for php that's 8+; if this
# is the inside loop (Valet runs itself 2x in some settings), skip
# checking and pulling again by reading the exported env var
if [[ $PHP_EXECUTABLE = "" ]]
then
    PHP=$(php $DIR/find-usable-php.php)

    # Validate output before running it on the CLI
    if [[ ! -f $PHP ]]; then
        echo "Error finding executable PHP. Quitting for safety."
        echo "Provided output from find-usable-php.php:"
        echo $PHP
        exit
    fi

    export PHP_EXECUTABLE=$PHP
else
    PHP=$PHP_EXECUTABLE
fi

$PHP "$DIR/src/index.php" "$@"
