#!/bin/bash
# piscal manager script

usage="$(basename "$0") [-h] -d directory_name [-f input_filename|-s] -- script to manage Piscal

where:
    -h  show this help text
    -d  working directory name
    -f  input filename
    -s  job status"

# http://stackoverflow.com/a/14203146/99492
# http://wiki.bash-hackers.org/howto/getopts_tutorial

# Initialize variables:
base_directory="/home/poprhythm/LeafWeb"
directory_name=""
input_filename=""
task="start" # default task
pid_filename="piscal.pid"
out_filename="piscal.out"
launcher="$base_directory/piscal_launcher.sh"

while getopts "hd:f:s" opt; do
    #echo "$opt = $OPTARG"
    case "$opt" in
    h )
        echo "$usage"
        exit
        ;;
    d )
        directory_name=$OPTARG
        ;;
    f )
        input_filename=$OPTARG
        task="start"
        ;;
    s )
        task="get_status"
        ;;
    \?) printf "illegal option: -%s\n" "$OPTARG" >&2
        echo "$usage" >&2
        exit 1
        ;;
    esac
done
if [ -z "$directory_name" ]; then
    echo "directory name required (-d)"
    exit 1
fi
working_directory="$base_directory/$directory_name"
if [ ! -d "$working_directory" ]; then
    echo "directory $working_directory not found"
    exit 1
fi
if [ "$task" = "start" ]; then
    if [ -z "$input_filename" ]; then
        echo "input filename required (-f)"
        exit 1
    fi
    
    if [ ! -f "$working_directory/$input_filename" ]; then
        echo "input filename $working_directory/$input_filename not found"
        exit 1
    fi
    
    command="$launcher -d $working_directory -f $input_filename"
    nohup ${command} > $working_directory/$out_filename 2>&1 &

    # write the PID to a temp file to check for completion later
    echo $! > $working_directory/$pid_filename
    echo started
elif [ "$task" = "get_status" ]; then
    pid_path="$working_directory/$pid_filename"
    
    # if the pid doesn't exist, then process never started
    if [ ! -f "$pid_path" ]; then
        echo "no pid file found"
        exit 1
    fi
    
    pid=$(head -n 1 $pid_path)
    # if the pid exists, check the process status using ps
    if ps -p $pid > /dev/null; then
        # if it is in ps, then it's still running
        echo running
    else
        # otherwise, it is complete, check the output for success/error
        # TODO: examine output for errors, etc
        #cat piscal.out
        if [ ! -d "$working_directory/output" ]; then
            echo "output directory $working_directory/output not found"
            exit 1
        fi
        echo success
        find "$working_directory/output"/*
    fi
fi