#!/bin/bash
# -*- mode: sh; c-basic-offset: 4; tab-width: 8; indent-tabs-mode: nil -*-
# vi: set shiftwidth=4 tabstop=8 softtabstop=4 expandtab:
# :indentSize=4:tabSize=8:noTabs=true:
# vim: filetype=sh

# ---- error handling
set -o errexit;
set -o posix;
set -o pipefail;
set -o errtrace;
unexpected_error() {
    local errstat=$?
    echo "${g_prog:-$(basename "$0")}: Error! Encountered unexpected error at 'line $(caller)', bailing out..." 1>&2
    exit $errstat;
}
trap unexpected_error ERR;

# Force the path to only what we need, saving off the original path
PATH_ORIG=$PATH;
PATH=/usr/bin:/bin

g_prog=$(basename "$0");
g_progdir=$(dirname "$0");
g_progdir_abs=$(dirname "$(readlink -f "$0")");

# ---- global env

. "$g_progdir_abs/../../private/runtime-common/lib/globalenv.ish"

# ---- usage

usage() {
    local exitstat=2;
    if [[ ! -z "${2:-}" ]] ; then
        if [[ ! $2 =~ [[:digit:]]+ ]] ; then
            minterror "usage(): exitstat ($2) must be numeric."
        fi
        exitstat=$2;
    fi

    # Only redirect to stderr on non-zero exit status
    if [[ $exitstat -ne 0 ]] ; then
        exec 1>&2;
    fi

    if [[ ! -z "${1:-}" ]] ; then
        echo "$g_prog: Error! $1"
    fi

    echo "Usage: $g_prog"
    echo "         --help          -- print this usage"
    echo ""

    if [[ $exitstat -ne 0 ]] ; then
        # Print error again, useful for long usages messages
        if [[ ! -z "${1:-}" ]] ; then
            echo ""
            echo "$g_prog: Error! $1"
        fi
    fi

    # bash only:
    if [[ $exitstat -ne 0 ]] ; then
        echo "  at: $(caller)";
    fi
    exit $exitstat;
}

# ---- error functions
merror() {
    echo "$g_prog: Error! ""$@" 1>&2;
    exit 1;
}
minterror() {
    echo "$g_prog: Internal Error! ""$@" 1>&2;
    exit 1;
}
mwarn() {
    echo "$g_prog: Warning! ""$@" 1>&2;
}

# ---- argument parsing

# Save off the original args, use as "${g_origargs[@]}" (with double quotes)
declare -a g_origargs;
g_origargs=( ${1+"$@"} )

opt_havesep=false;
for opt in ${1+"$@"}; do [[ x"$opt" == x"--" ]] && opt_havesep=true; done

# Ignore any unrecogninzed arguments, just pass them to the subprogram
declare -a opt_subargs;

while [[ $# != 0 ]]; do
    opt="$1"; shift;
    case "$opt" in
        # Flag with no argument example:
        #   --flag|--fla|--fl|--f)
        #     opt_flag=true;
        # Option with argument example:
        #   --arg|--ar|--a)
        #     [ $# -eq 0 ] && usage;
        #     opt_somearg=$1; shift;;
        -h|-help|--help|--hel|--he|--h) usage "" 0;;
        --)
            # We have a separator. Pass everything after the separator to
            # the subprogram, with the exception of the tarball (removed
            # below).
            opt_subargs=( ${1+"$@"} ); break;;
        *)
            # Unrecognized arguments.  If we have a ("--") separator in the
            # arglist, then issue an error.  If we don't have a separator,
            # then just pass any unrecognized arguments to the subprogram.
            if $opt_havesep; then
                usage "Unrecognized argument: $opt"
            else
                opt_subargs=( "${opt_subargs[@]}" "$opt" );
            fi
            ;;
    esac
done

# ---- globals

# ---- subroutines

cleanup_on_exit() {
    local dir;
    local file;
    for file in $g_cleanup_files; do
        /bin/rm -f "$file";
    done
    for dir in $g_cleanup_dirs; do
        /bin/rm -rf "$dir";
    done
}


# ---- main

g_smrt_topdir=$(readlink -f "$g_progdir/../..");
g_smrt_rootdir=$(readlink -f "$g_smrt_topdir/../..");

g_versionstr_full=$(cat "$g_smrt_topdir/etc/versionstr.txt")

rm -f "$g_smrt_rootdir/new"
ln -s "install/$g_versionstr_full" "$g_smrt_rootdir/new"


success_file=$(mktemp -u -t "$g_prog.success.XXXXXXXXXX");

# Make sure we clean up the tmp dir on exit
g_cleanup_files="$g_cleanup_files $success_file";
trap cleanup_on_exit EXIT;

# Fire up the installprompter (in 'upgrade' mode)
stat=0
eval 'PATH="$PATH_ORIG" SMRT_SUCCESS_FILE="$success_file" $envvars "$g_smrt_topdir/admin/bin/installprompter" --reconfig --rootdir "$g_smrt_rootdir" "${opt_subargs[@]}" || stat=$?'
if [[ $stat -ne 0 ]] ; then
    exit $stat;
fi

# Test to see if everything worked succesfully by checking the existence of
# the SMRT_SUCCESS_FILE.  If it exists (success), remove the 'new' and 'prior'
# links and create the 'current' and 'admin' links.  If not, leave the 'new'
# and 'prior' links.
if [[ -e "$success_file" ]] ; then
    # Everything worked successfully, create the 'current' and admin links:
    rm -f "$g_smrt_rootdir/current"
    mv "$g_smrt_rootdir/new" "$g_smrt_rootdir/current"
    rm -f "$g_smrt_rootdir/admin"
    ln -sf "current/admin" "$g_smrt_rootdir/admin"
    rm -f "$g_smrt_rootdir/prior"
fi

exit 0;
