#!/usr/bin/env bash

# Desired command.
Y_COMMAND=${1}
# Path of phpyoke script.
Y_PATH=$(which yokephp)
# Path of active PHP.
Y_PHP_PATH=$(which php)

# If the current command is to connect.
if [ "${Y_COMMAND}" == "connect" ] || [ "${Y_COMMAND}" == "c" ]; then
    # save the execution return into a variable for later parsing.
    Y_RETURN=$(${Y_PHP_PATH} "${Y_PATH}" "${Y_COMMAND}" "${@: 2}")
else
    # If the command is other than connect, pass through.
    ${Y_PHP_PATH} "${Y_PATH}" "${Y_COMMAND}" "${@: 2}"
    # Define a empty Y_RETURN
    Y_RETURN=""
fi

# If the return starts with ssh.
if [[ ${Y_RETURN} =~ ^ssh.* ]]; then
    # Execute the returned line into the terminal (connect).
    eval "${Y_RETURN}"
fi

# If the return starts with Password.
if [[ ${Y_RETURN} =~ ^Password.* ]]; then
    # Break the return into the password helper and command variables.
    Y_PASSWORD_HELPER=$(echo -e "${Y_RETURN}" | awk 'NR==1')
    Y_PASSWORD_COMMAND=$(echo -e "${Y_RETURN}" | awk 'NR==2')

    # Display the password
    echo "${Y_PASSWORD_HELPER}"
    # Connect
    eval "${Y_PASSWORD_COMMAND}"
fi
