#!/bin/bash


usage(){
cat << EOF
$0 - runs OMA standalone

$0 [options] [paramfile]

Runs the standalone version of the Orthologous MAtrix (OMA) pipeline
to infer orthologs among complete genomes. A highlevel description
of its algorithm is available here: http://omabrowser.org/oma/about

The all-against-all Smith-Waterman alignment step of OMA requires 
a lot of CPU time. OMA standalone can therefore be run in parallel.
If you intend to use OMA standalone on a HPC cluster with a scheduler
such as LSF, PBS Pro, Slurm or SunGridEngine, you should use the 
jobarray option of those systems,
e.g. bsub -J "oma[1-500]" $0 (on LSF).
     qsub -t 1-500 $0 (on SunGridEngine)
In case you run OMA on a single computer with several cores, use 
the -n option.

Options:
  -n <number>   number of parallel jobs to be started on this computer
  -v            version
  -d <level>    increase debug info to <level>. By default level is set to 1.
  -i            interactive session, do not quit in case of error and at the end
                of the run.
  -s            stop after the AllAll phase. This is the part which is parallelized.
                The option can be useful on big datasets that require lot of 
                memory for the later phases of OMA. It allows to stop after the 
                parallelized step and restart again a single process with more
                memory.
  -c            stop after database conversion. This option is useful if you 
                work with a large dataset and/or the filesystem you use is 
                slow. 
  -W <secs>     maximum amount of Wall-clock time (in secs) that the job should
                run before terminating in a clean way. This option has only an 
                effect in the all-against-all phase. If the job terminates
                because it reaches the time limit, it quits with the exit
                code 99.
  -p            copy the default parameter file to the current directory. This
                is useful if want to analyse a new dataset and previously 
                installed OmaStandalone.
  -h/?          this help

paramfile       path to the parameter file. it defaults to ./parameters.drw


EXIT
   0            normal exit
   1            a general error (i.e. configuration problem) occured
  99            reached timelimit (provided with -W flag)

EOF
}

realpath() {
    canonicalize_path "$(resolve_symlinks "$1")"
}

resolve_symlinks() {
    local dir_context path
    path=$(readlink -- "$1")
    if [ $? -eq 0 ]; then
        dir_context=$(dirname -- "$1")
        resolve_symlinks "$(_prepend_path_if_relative "$dir_context" "$path")"
    else
        printf '%s\n' "$1"
    fi
}

_prepend_path_if_relative() {
    case "$2" in
        /* ) printf '%s\n' "$2" ;;
         * ) printf '%s\n' "$1/$2" ;;
    esac
}

canonicalize_path() {
    if [ -d "$1" ]; then
        _canonicalize_dir_path "$1"
    else
        _canonicalize_file_path "$1"
    fi
}

_canonicalize_dir_path() {
    (cd "$1" 2>/dev/null && pwd -P)
}

_canonicalize_file_path() {
    local dir file
    dir=$(dirname -- "$1")
    file=$(basename -- "$1")
    (cd "$dir" 2>/dev/null && printf '%s/%s\n' "$(pwd -P)" "$file")
}


# $OMA_PATH points to the folder containing the current
# version of OMA.
OMA_PATH="$(realpath "$(dirname "$(realpath $0)")/..")"

paramerror="

I found an error in your parameter file.
Most probably, you missed a semicolon at the end of a line.

Please fix it and try again."

pfile="./parameters.drw"
wdir="./"
dbglevel="1"
NProc="1"
localParallel="0"
darwin_flag="-E -q"
interactive=""
earlyStop="false"
convOnly="false"
while getopts "hn:vd:iscW:p" opt ; do
    case $opt in 
    h) usage
         exit 0
         ;;
    n)   NProc="$OPTARG"
         if ! [[ $NProc =~  ^[1-9][0-9]*$ ]] ; then
             echo "-$opt requires positive integer as argument" >&2
             usage
             exit 1
         fi
         localParallel=1
         ;;
    d)   dbglevel="$OPTARG"
         if ! [[ $dbglevel =~  ^[1-9][0-9]*$ ]] ; then
             echo "-$opt requires positive integer as argument" >&2
             usage
             exit 1
         fi
         ;;
    v)   echo "OMA version 2.5.0"
         exit 0
         ;;
    i)   darwin_flag=""
         interactive="interactive"
         ;;
    s)   earlyStop="true;"
         ;;
    c)   convOnly="true;"
         ;;
    W)   maxtime="$OPTARG"
         if ! [[ $maxtime =~ ^[1-9][0-9]*$ ]] ; then
              echo "-$opt requires a positive integer value as argument" >&2
              usage
              exit 1
         fi
         ;;
    p)   cp -i $OMA_PATH/parameters.drw .
         exit 0
         ;;
    \?)  echo "invalid option" >&2
         usage
         exit 1
         ;;
    :)   echo "option -$OPTARG requires an argument" >&2
         usage
         exit 1
         ;;
    esac
done
shift $((OPTIND-1))
echo $@

if [ -n "$1" ] ; then 
    pfile="$1"
fi

if [ ! -e $pfile ] ; then
    echo "Could not find parameter file!" >&2
    exit 1
fi

if [[ -n "$interactive" && $localParallel == "1" && $NProc -gt "1" ]]; then
    echo "interactive mode only possible without parallelism."
    exit 1
fi

if [ -z "$maxtime" ] ;then maxtime="DBL_MAX"; fi

set -o monitor
trap cleanup EXIT INT

cleanup() {
    children=$(jobs -lp)
    if [ -n "$children" ];then
        kill $children
    fi
}

drw_cmds=$(cat << EOC
libdir := '$OMA_PATH/lib/': 
e := traperror(ReadProgram('$pfile')): 
if e=lasterror then print('$paramerror'): exit(1): fi: 
loaded_params := [e]:
printlevel := $dbglevel: 
OMA_STANDALONE_VERSION := '2.5.0':
only_run_allall := $earlyStop:
only_run_dbconv := $convOnly:
stop_at_time := UTCTime() + $maxtime:
ReadProgram('$OMA_PATH/OMA.drw'):
EOC
)

cat $OMA_PATH/lib/splashscreen.txt
if [ -n "$interactive" ] ; then
    # run interactive, i.e. no background, no done stmt 
    exec $OMA_PATH/bin/omadarwin ${darwin_flag} << EOA
    $drw_cmds
EOA
elif [ "${NProc}" = "1" ] ; then
    exec $OMA_PATH/bin/omadarwin ${darwin_flag} << EOB
    $drw_cmds
    done;
EOB
else
    for pNr in $(eval echo {1..${NProc}}) ; do
        if [ "$localParallel" -gt 0 ] ; then
            OneMachineParallelInfo="NR_PROCESSES := $NProc; THIS_PROC_NR := $pNr;"
        fi
        $OMA_PATH/bin/omadarwin ${darwin_flag} << EOF &
        ${OneMachineParallelInfo}
        $drw_cmds
        done;
EOF
    done
    wait
fi
