#!/usr/bin/env bash
set -u
DIR_ORTHOLOGER=${DIR_ORTHOLOGER:="$(cd -P "$(dirname "${BASH_SOURCE[0]}")"/../ && pwd)"}
generate_version() {
    local gitexe=$(which \git)
    local ec=1
    if [[ -x $gitexe ]]; then
        # a dummy call to check we have a git version control

        cd "$DIR_ORTHOLOGER" || return 255
        git status >& /dev/null
        if [[ $? -eq 0 ]]; then
            # get the latest non-tip tag
            hashlatest=$(git rev-list --all --max-count=1)
            taglatest=$(git describe --tags $hashlatest 2>/dev/null)
            tagshort=$(git describe --abbrev=0 --tags $hashlatest 2>/dev/null)
            tagdate=$(git log -1 --format=%ai $hashlatest)

            # if no tag... (e.g checkout of head)
            [[ -n $taglatest ]] || taglatest=$hashlatest
            [[ -n $tagshort  ]] || tagshort=$hashlatest
        
            echo "OP_VERSION=\"$taglatest\""
            echo "OP_VERSION_SHORT=\"$tagshort\""
            echo "OP_VERSION_HASH=\"$hashlatest\""
            echo "OP_VERSION_DATE=\"$tagdate\""
            ec=0
        fi
    fi
    if (( ec == 1 )); then
        echo "OP_VERSION=\"<not in a git repo>\""
        echo "OP_VERSION_HASH=\"\""
        echo "OP_VERSION_SHORT=\"\""
        echo "OP_VERSION_DATE=\"\""
    fi
    cd - >& /dev/null
    return $ec
}
ftmp=$(mktemp "$DIR_ORTHOLOGER/bin/version_XXXXXX" 2>/dev/null)
if [[ -f "$ftmp" ]]; then
    created=0
    fver="$DIR_ORTHOLOGER/bin/version.sh"
    generate_version > "$ftmp"
    ec=$?
    if [[ $ec -eq 0 ]]; then
        # in git repo -> (re)create version.sh
        \cp -f "$ftmp" "$fver"
        created=1
    elif [[ $ec -eq 1 ]]; then
        # outside git repo -> create only if it does not exist
        [[ -f "$fver" ]] || {
            \cp -f "$ftmp" "$fver"
            created=1
        }
    else
        # this should never happen!
        echo "FATAL: failed to generate version.sh in $DIR_ORTHOLOGER/bin" 1>&2
        rm -f $ftmp
        exit 255
    fi
    if (( created == 1 )); then
        ###echo "generated version.sh at $fver" 1>&2
        chmod 755 $fver
    fi
fi
rm -f $ftmp

