#!/usr/bin/env bash
echo
echo "NEEDS SOME REVISION"
echo
exit 255
set -u

# get required executables
PYTHON3=$(/usr/bin/which python3)
GET_TREE=$DIR_ORTHOLOGER/bin/get_orthodb_tree.py
GEN_RUNS=$DIR_ORTHOLOGER/bin/generate_runs.py    # SHOULD NOT USE THIS ONE! Replace by above cmd

# check nr of arguments
[[ $# -ge 3 ]] || { echo "usage: $0 <tree JSON or URL> <root label> <output dir>"; exit 0; }
TREE_INPUT=$1
TREE_ROOT=$2
DIR_OUTPUT=$3
ODBVER=${4-'current'}

# check output tree
TREE_FILE="$DIR_OUTPUT/${TREE_ROOT}.nw"

# check input tree spec
TREE_INPUT_JSON=""
TREE_INPUT_ODB=""
if [[ -f "$TREE_INPUT" ]]; then
    TREE_INPUT_JSON="$TREE_INPUT"
else
    if [[ "${TREE_INPUT:0:8}" == "https://" ]]; then
	    TREE_INPUT_ODB="$TREE_INPUT/${ODBVER}/tree"
    else
	    echo "error: tree input is neither a file nor a URL"
	    echo "the URL should point to the orthodb API tree function, e.g:"
	    echo " https://data.orthodb.org/$ODBVER/tree"
	    exit 255
    fi
fi

[[ -x $GET_TREE    ]] || { echo "error: missing executable script $GET_TREE"; exit 255; }
[[ -x $GEN_RUNS    ]] || { echo "error: missing executable script $GEN_RUNS"; exit 255; }

#-----------------------------------------------
# CLUSTER TREE
# create newick tree for given root in PL_TODO
#-----------------------------------------------
create_tree() {
    [[ -f $TREE_FILE ]] && { echo "skip creating tree file - it already exists at $TREE_FILE"; return 0; }
    
    # first get the json if not there
    if [[ ! -f "$TREE_INPUT_JSON" ]]; then
	TREE_INPUT_JSON="$DIR_OUTPUT/orthodb_tree.json"
        if [[ -z "$TREE_INPUT_ODB" ]]; then
            echo "error: unable to load OrthoDB tree - TREE_INPUT_ODB is not set!"
            echo "error: for OrthoDB v10.1 the url is: https://v101.orthodb.org/tree"
            return 255
        fi
        echo "-> downloading OrthoDB tree from $TREE_INPUT_ODB"
        
        $PYTHON3 $GET_TREE -u "$TREE_INPUT_ODB" 2> /dev/null 1> "$TREE_INPUT_JSON"
        [[ $? -eq 0 ]] || {
            rm -f "$TREE_INPUT_JSON" >& /dev/null
            echo "unable to load OrthoDB tree - check network connection!"
            echo "if no connection, retrieve it elsewhere and save it at $TREE_INPUT_JSON"
            echo "error: command used: $GET_TREE -u $TREE_INPUT_ODB"
            return 255
        }
    fi
    # get tree, include leaves (ie species taxids)
    echo "->generating tree newick file: $TREE_FILE"
    opts="-j $TREE_INPUT_JSON -L"
    [[ -z "$TREE_ROOT" ]] || opts="$opts -r $TREE_ROOT"
    $PYTHON3 $GET_TREE $opts 2> /dev/null 1> $TREE_FILE
    [[ $? -eq 0 ]] || {
        rm -f $TREE_FILE >& /dev/null
        echo "error: unable to create tree for label <$PL_TODO_NAME>"
        echo "error: command used: $GET_TREE $opts"
        echo "error: note that the label must be a valid taxid present in the OrthoDB tree"
        echo "error: this error implies that the taxid in NOT present"
        return 255
    }
    return 0
}

remake_target() {
    local target=$1
    local source=$2
    
    # target does not exist
    [[ -f $target ]] || return 0
    
    # target is NOT newer than source
    [[ $target -nt $source ]] || return 0

    # target exists and is newer than source
    return 1
}
#-----------------------------------------------
# CLUSTER TREE
# create todo files from tree
#-----------------------------------------------    
create_todos() {
    [[ -f $TREE_FILE ]] || {
        echo "error: cannot find tree at $TREE_FILE"
        echo "error: create_todos() must be run before create_todos()"
        return 255
    }
    local nfound=0
    local ncreated=0
    local x=
    for x in $($PYTHON3 $GEN_RUNS -t "$TREE_FILE" -N -k); do
        local f=${DIR_OUTPUT}/${x}.todo
        nfound=$((nfound+1))
        remake_target "$f" "$TREE_FILE" || continue
        echo "->generating todo file: $f"
        $PYTHON3 $GEN_RUNS -t "$TREE_FILE" -L -k -r $x | sort -u > "$f"
        [[ $? -eq 0 ]] || {
            rm -f $f >& /dev/null
            echo "error: unable to create todo file $f"
            echo "error: command used: $GEN_RUNS -t $TREE_FILE -L -k -r $x"
            return 255
        }
        ncreated=$((ncreated+1))
    done
    echo "->created $ncreated todo files out $nfound possible"
    return 0        
}


create_tree
create_todos
