#!/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;
set -o nounset;

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;

# ---- 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;
}

# ---- 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 [--help] \\"
    echo "              --install|--upgrade|--reconfigure"
    echo ""
    echo "         --install        -- initialize after fresh install"
    echo "         --upgrade        -- initialize after upgrade"
    echo "         --reconfigure    -- initialize after reconfigure"
    echo "         -h|--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;
}

# ---- argument parsing

achk() {
    if [[ $1 -eq 0 ]] ; then usage "Missing argument to $2 option"; fi
}

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

    opt_install=false;
    opt_upgrade=false;
    opt_reconfigure=false;
    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;;
            --install) opt_install=true;;
            --upgrade) opt_upgrade=true;;
            --reconfig|--reconfigure)  opt_reconfigure=true;;
            -h|-help|--help|--hel|--he|--h) usage "" 0;;
            -*) usage "Unrecognized option: $opt";;
            *)
                local argstr=${1+"$@"};
                usage "Unexpected extraneous arguments detected: $opt $argstr"
                ;;
        esac
    done

    # Disable this check for now, so we can just call smrtlink-init (since
    # is is no longer being called from the installer).  At this point there
    # should be no diference between install, upgrade and reconfigure as far
    # as initializing smrtlink is concerned (we just run import-canneddata)
    #
    #   if  ( $opt_install && $opt_upgrade ) ||
    #       ( $opt_install && $opt_reconfigure ) ||
    #       ( $opt_upgrade && $opt_reconfigure ) ; then
    #       usage "Must only specify one of --install, --upgrade or --reconfigure"
    #   fi
    #   if ! $opt_install && ! $opt_upgrade && ! $opt_reconfigure; then
    #       usage "Must specify one of --install, --upgrade or --reconfigure"
    #   fi
}

# ---- globals

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

    # Force the path to only what we need (/sbin needed for ifconfig)
    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"
}

set_globals() {
#    g_topdir="$g_progdir/../.."
    :
}

# ---- subroutines

# ---- main

set_preglobals ${1+"$@"};
parseargs ${1+"$@"};
set_globals;

# Note, at this point, we will always run the initialize, regardless if
# we are installing, updating or reconfiguring (on the assumption that there
# is no harm in running any of the initialization steps extraneously).

# We may be able to avoid the initalization step for the reconfgure case,
# since we don't expect anything to change.  But for now, we will still
# initialize (so we may be able to use --reconfigure to recover from an
# install or upgrade that ended in error).
# To skip initialization in the reconfigure case, enable this conditional:
#
#    if [[ $opt_reconfigure ]] ; then
#        exit 0;
#    fi

#
# Initalize smrtlink
#

# The procedure will be:
#     - check status of all smrtlink gui and smrtlink services daemons
#     - if daemons are running and properly functioning
#           proceed
#       else
#           shutdown all daemons (smrtlink gui, smrtlink services)
#           start all daemons (smrtlink gui, smrtlink services)
#     - Run initialization steps, for example
#           import-canneddata
#     - if daemons were started/restarted
#           shutdown all daemons (smrtlink gui, smrtlink services)


# Check status of daemons
stat=0
"$g_progdir/services-status" --quiet || stat=$?

restart_daemons=false;
if [[ $stat -ne 0 ]] ; then
    restart_daemons=true;
fi

# Restart daemons, if necessary
if $restart_daemons; then
    # Stop all daemons
    stat=0
    "$g_progdir/services-stop" || stat=$?
    # Ignore any errors here (we may already be stopped), and the current
    # implementation of 'services-stop' will return an error in this case.

    # Start all daemons
    stat=0
    "$g_progdir/services-start" || stat=$?
    if [[ $stat -ne 0 ]]; then
        merror "Encountered error in starting all daemons, exiting..."
    fi
fi

# Run initization steps
echo "Initializing smrtlink..."

echo "   Running import-canneddata..."
stat=0
"$g_progdir/import-canneddata" || stat=0
if [[ $stat -ne 0 ]]; then
    merror "Error in running import-canneddata, exiting..."
fi

# Shutdown daemons, if necessary
# If we started or restarted daemons, shut them down.  Else leave them running.
if $restart_daemons; then
    # Stop all daemons
    stat=0
    "$g_progdir/services-stop" || stat=$?
    if [[ $stat -ne 0 ]]; then
        merror "Encountered error in stopping all daemons after initialization, exiting..."
    fi
fi
