#!/bin/sh

max_num_of_workers=100
parameters=""
makeflow_ops=""
num_of_workers=1

show_help()
{
	echo "Use: uge_submit_makeflow [options] <project-name> <makeflow-script>"
    echo "It requires a catalog server to work properly."
	echo "options:"
	echo "  -p <parameters>     UGE qsub parameters. May be used several times."
	echo "  -E <parameters>     Extra options for makeflow. May be used several times."
    echo "  -w <number>         Submit <number> workers. (Default is $num_of_workers)"
	echo "  -h                  Show this help message."
}


while getopts E:p:w:h opt
do
	case "$opt" in
		E)  makeflow_ops="$makeflow_ops $OPTARG";;
		p)  parameters="$parameters $OPTARG";;
		w)  num_of_workers=$OPTARG;;
		h)  show_help; exit 0;;
		\?) show_help; exit 0;;
	esac
done

shift $(expr $OPTIND - 1)

if [ $# = 2 ]; then
	project_name=$1
	makeflow_script=$2
else
	show_help
    exit 1
fi

makeflow=`which makeflow 2>/dev/null`
if [ $? != 0 ]; then
	echo "$0: please add 'makeflow' to your PATH."
	exit 1
fi

qsub=`which qsub 2>/dev/null`
if [ $? != 0 ]; then
	echo "$0: please add 'qsub' to your PATH."
	exit 1
fi

if [ ! -e $makeflow_script ]; then
	echo "Makeflow script - $makeflow_script does not exist."
	exit 1
fi


if [ $num_of_workers -ne 0 ]; then
    uge_submit_workers=`which uge_submit_workers 2>/dev/null`
    if [ $? != 0 ]; then
        echo "$0: please add 'uge_submit_workers' to your PATH."
        exit 1
    else
        if [ $num_of_workers -gt $max_num_of_workers ]; then
            $num_of_workers = $max_num_of_workers
        fi
        if [ -n "$parameters" ]; then
            uge_submit_workers -a -N $project_name -p "$parameters" $num_of_workers
        else
            uge_submit_workers -a -N $project_name $num_of_workers
        fi
    fi
fi
echo $num_of_workers workers have been submitted to UGE.


cp $makeflow .

cat >uge_submit.sh <<EOF
#!/bin/sh
./makeflow -a -T wq $makeflow_ops -M "$project_name" $makeflow_script
EOF

chmod 755 uge_submit.sh

qsub $parameters uge_submit.sh

