#!/usr/bin/env bash

SOURCE="${BASH_SOURCE[0]}"
echo $SOURCE
exit

# Resolve possible symbolic link (http://stackoverflow.com/a/246128/416354)
while [ -h "$SOURCE" ]; do
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done

DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

# Correct path if we are globally installed via Composer
if [ ! -f "$DIR/cli/valet.php" ]
then
    OLDPWD="$PWD"
    cd "$DIR/../laravel/valet"
    DIR="$(pwd)"
    cd "$OLDPWD"
fi

if [[ "$1" = "install" ]] || [[ "$1" = "domain" ]] || [[ "$1" = "start" ]] || [[ "$1" = "restart" ]] || [[ "$1" = "stop" ]] || [[ "$1" = "uninstall" ]]
then
    if [[ "$EUID" -ne 0 ]]
    then
        sudo $SOURCE "$@"
    else
        php "$DIR/cli/valet.php" "$@"
    fi
elif [[ "$1" = "update" ]]
then
    bash <(curl -s https://raw.githubusercontent.com/laravel/valet/master/cli/scripts/update.sh)
elif [[ "$1" = "share" ]]
then
    HOST="${PWD##*/}"
    DOMAIN=$(php "$DIR/cli/valet.php" current-domain)


    for linkname in ~/.valet/Sites/*; do
        RESOLVED_LINK="$(readlink $linkname)"

        if [[ "$RESOLVED_LINK" = "$PWD" ]]
        then
            HOST="${linkname##*/}"
        fi
    done

    # Fetch Ngrok URL In Background...
    bash "$DIR/cli/scripts/fetch-share-url.sh" &

    "$DIR/bin/ngrok" http -host-header=rewrite "$HOST.$DOMAIN:80"
else
    php "$DIR/cli/valet.php" $@
fi
