#!/bin/bash

master_branch=vault
scripts_branch=scripts
root_version=3
root=

export TOP_PID=$$

is_trace=false
if [ "x$VAULT_TRACE" != "x" ]; then
  is_trace=true
fi

function trace {
    if $is_trace; then
        echo "`basename $0`: ${@:1}" 1>&2;
    fi
}


normal_cleanup="true"
failed_cleanup="true"
is_failed=false

function on_normal_exit
{
    if $is_failed; then
        exit 1
    else
        trace "Normal exit from $BASHPID"
        trace "Exec: $normal_cleanup"
        eval "$normal_cleanup"
        exit 0
    fi
}

is_exit_on_failure=true
is_expect_success=true
function on_failure
{
    if $is_expect_success; then
        trace "Failure cleanup in $BASHPID"
        trace "Exec: $failed_cleanup"
        is_failed=true
        eval "$failed_cleanup"
        $is_exit_on_failure && exit 1
    else
        trace "Failure is expected"
        is_failed=true
    fi
}
trap on_failure TERM
trap on_normal_exit EXIT
#trap on_failure ERR

function warn {
    echo "`basename $0`: Warning: ${@:1}" 1>&2;
}

function error {
    TOP_RC=$1
    echo "`basename $0`: Error #$1: ${@:2}" 1>&2;
    if [ $BASHPID -ne $TOP_PID ]; then
        trace "Not a top script"
        is_exit_on_failure=false
        on_failure
    fi
    warn "Killing $TOP_PID"
    kill -s TERM $TOP_PID
}

update_path () {
    local my_path=$(dirname $1)
    my_path=$(readlink -f $(cd $my_path;pwd))
    if ! (echo $PATH | grep "^$my_path:.*" 1>/dev/null); then
        export PATH=$my_path:$PATH
    fi
    if [ "x$VAULT_LIB_DIR" != "x" ]; then
        [ -d $VAULT_LIB_DIR ] || error 6 "No such dir $VAULT_LIB_DIR"
        local lib_path=$(readlink -f $VAULT_LIB_DIR)
        if [ "$my_path" != "$lib_path" ]; then
            export PATH=$lib_path:$PATH
        fi
    fi
    trace "SCRIPTS PATH: $PATH"
}
update_path $0

function ensure_param_count_op_exit_usage {
    [ $# -ge 3 ] || error 22 "Call as Num#0 OP Num#1"
    if ! [ $1 $2 $3 ]; then
        local name=`basename $0`
        echo "Expecting param count: $1 $2 $3" 1>&2;
        echo "Params was: ${@:5}" 1>&2;
        echo "Usage: $name $4" 1>&2;
        exit $1
    fi
}

function ensure_param_count_exit_usage {
    ensure_param_count_op_exit_usage $1 -eq $2 ${@:3}
}

function tree_version_path {
    [ $@ ] || error 22 "Call with root"
    echo $1/.vault
}

function repo_version_path {
    [ $@ ] || error 22 "Call with root"
    echo $1/.git/vault.version
}

function units_path {
    [ $@ ] || error 22 "Call with root"
    echo $1/.units/
}

function get_root {
    current_root=$1
    while true; do
        current_root=$(cd $current_root && git rev-parse --show-toplevel)
        if [ $? -ne 0 ] || [ "x$current_root" == "x" ] ||
               ! [ -d "$current_root" ] ; then
            error 1 "Not a git $1"
        fi
        if [ -f $current_root/.vault ]; then
            echo $current_root
            break
        else
            [ "$(readlink -f $current_root)" == "/" ] &&
                error 33 "Reached /, vault is not found"
            current_root=$(dirname $current_root)
        fi
    done
}

function init_root {
    if [ "x$root" == "x" ]; then
        root=$(get_root $(pwd))
        if [ $? -ne 0 ]; then
            error $? "Not inside vault? $(pwd)"
        fi
        if [ "x$root" == "x" ]; then
            error 54 "Root is empty"
        fi
    fi
    version_file=$(tree_version_path $root)
    test -f "$version_file" || error 44 "Not a vault tree $root?"

    tree_version=$(cat $version_file)
    if [ "x$tree_version" == "x" ]; then
        error 10 "Empty tree version for $root"
    fi
    trace "Tree version $tree_version"
}

function init_root_and_enter {
    init_root
    cd $root || error 2 "Can't enter $root"
}

function get_vid {
    init_root
    git config --file $root/.git/config vault.id
}

function get_current_branch {
    echo $(git rev-parse --abbrev-ref HEAD)
}

function vault_exec {
    init_root
    local fname=$1
    local log_file=$root/.vault/logs/$2
    test -x $fname || error 77 "File is not an exec: $fname"
    local cur_dir=$(pwd)
    trace "Exec: ls -al $fname"
    local out_file=$log_file-out.txt
    local err_file=$log_file-err.txt
    touch $out_file
    touch $err_file
    $fname 1>$out_file 2> $err_file || error $? "File execution is failed: $fname"
    if [ "$(pwd)" != "$cur_dir" ]; then
        error 54 "Executable changed cwd to $(pwd)"
    fi
}

function date_tag {
    echo $(date +%Y-%m/%d/%Z/%H-%M/%S.%N)
}

function unique_tag {
    echo $(uuidgen)
}

function units {
    find .units -type f -name '*.json' -exec basename {} '.json' \;
}

function split_git_uri {
    local uri=$1
    trace "split $uri"
    # parsing is too dumb now, it should be stricter
    ssh_re='(ssh://)?((.*)@)?(.*[^\\]):([0-9]*)(.*)'
    if [[ "$uri" =~ $ssh_re ]]; then
        trace "Remote URI is ssh"
        user="${BASH_REMATCH[3]}"
        host="${BASH_REMATCH[4]}"
        port="${BASH_REMATCH[5]}"
        src_repo="${BASH_REMATCH[6]}"
        src_type=ssh
    elif [[ $uri =~ (file://)?(.*) ]]; then
        trace "Assume URI is the local path"
        path="${BASH_REMATCH[2]}"
        src_repo=$path
        src_type=local
    fi
    if [ "x$user" == "x" ]; then
        user=$(whoami)
    fi
}

function get_data_dir {
    ensure_param_count_exit_usage $# 2 "get_data_dir <repo> <unit>"
    echo $1/$2/data
}

function get_blobs_dir {
    ensure_param_count_exit_usage $# 2 "get_blobs_dir <repo> <unit>"
    echo $1/$2/blobs
}

function get_snapshots {
    ensure_param_count_exit_usage $# 1 "get_snapshots <repo>"
    vault -a list-snapshots -V $1
}

vault_misc=1
function get_vault_lock_cmd {
    # wait for 30s
    echo "flock -w 30 -x $root/.vault.lock $@"
}
export -f get_vault_lock_cmd
