#! /bin/bash

#Detect curl absence
hash curl 2>/dev/null || {
    echo -e "\nPlease intall 'curl' first.\n";
    exit 1;
}

#Load last success host
if [ -f ~/.gan_host ];then
    last_host=`cat ~/.gan_host`
    host=$last_host
fi

#Detect arguments
while getopts ":h:lk:" opt; do
    case $opt in
        h)
            #Change host
            host=$OPTARG
            if [ "X${host}" != "X${last_host}" ];then
                echo $host > ~/.gan_host
            fi
            ;;
        l)
            #List tasks
            action="_gan_running()"
            ;;
        k)
            #Kill task
            action="_gan_kill('$OPTARG')"
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            exit 1
            ;;
        :)
            echo "Option -$OPTARG requires an argument." >&2
            exit 1
            ;;
    esac
done
shift $((OPTIND-1))

#Detect null host
if [ -z $host ];then
     echo "Please specify host using -h switch."
fi

#Curl output pipe
tmp=`mktemp -d`
trap 'rm -rf $tmp' EXIT INT TERM HUP
pipe="${tmp}/pipe"
mkfifo $pipe

if [ -z "$action" ];then
    #Detect null argument
    if [ -z "$1" ];then
        echo -e """
\E[1mGrooveAdmiN bash client\E[0m at \E[1;33m${host}\E[0m

Usage:
 $0             Show this message
 $0 <file>      Upload script file and run on server
 $0 -h <host>   Specify server address
 $0 -l          List all running tasks
 $0 -k <uuid>   Kill specify task

"""
        exit 1;
    fi

    #Detect file absence
    if [ ! -f $1 ];then
        echo "File '$1' does not exists."
        exit 1
    fi


    #Confirm
    echo -n -e """
\E[44m`cat $1`\E[0m

Contents above will be evalutated at \E[1;33m${host}\E[0m
\E[1mAre you sure? [Y/N]:\E[0m"""

    read -n 1

    if [[ ! $REPLY =~ ^[Yy]$ ]]
    then
        echo
        exit 1
    fi

    echo -e """
\E[1;34mEvaluating '$1' on server...\E[0m
"""

    #Post file
    cat ${pipe} &
    http_code=`curl -s -N -X POST "${host}" -T $1 -o ${pipe} -w '%{http_code}'`
else
    #Post predefined command
    cat ${pipe} &
    http_code=`curl -s -X POST "${host}" -d "${action}" -o ${pipe} -w '%{http_code}'`
fi

RET=$?
if [ "X${RET}" != "X0" ];then
    echo -e "\E[1;31mError:\E[0m Error connecting to server."
fi
if [ "X${http_code}" != "X200" ];then
    echo -e "\E[1;33mWarning:\E[0m Server returned http status \E[1m${http_code}\E[0m."
else
    echo -e "\E[1;32mCompleted!\E[0m"
fi