#!/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

# ---- usage

# ---- argument parsing

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

parseargs() {
    opt_port=""

    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)
            #     achk $# $opt; opt_somearg=$1; shift;;
            --port) achk $# $opt; opt_port=$1; shift;;
        esac
    done
}

# ---- subroutines

# ---- globals

set_preglobals() {
    # 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=$(readlink -f "$g_progdir");
}


set_globals() {
    g_topdir=$(readlink -f "$g_progdir_abs/../..")
    g_path="/usr/bin:/bin"
    g_javahome="$g_topdir/bundles/smrtlink-analysisservices-gui/current/private/thirdparty/java/jre/jre_8u192b12-hotspot"
    g_sltoolsbin="$g_topdir/bundles/smrtlink-analysisservices-gui/current/private/pacbio/smrtlink-analysisservices-gui/tools/bin"
    g_serverconfig_file="$g_topdir/bundles/smrtlink-analysisservices-gui/current/private/pacbio/smrtlink-analysisservices-gui/smrtlink-system-config.json"

    g_exe="$g_sltoolsbin/accept-user-agreement"

    g_python3_exe="$g_topdir/bundles/smrttools/current/private/thirdparty/python3/python3_3.7.3/binwrap/python3"

    # Set defaults based on configuration
    g_opts=();

    # port
    # If --port is specified on the command line, use it without modification.
    # If --port is not specified, compute it from the current smrtlink config
    # and supply it on the underlying command line
    if [[ -z "$opt_port" ]] ; then
        local port=$opt_port;
        port=$("$g_python3_exe" -c "import json; d = json.load(open('$g_serverconfig_file')); print(d['smrtflow']['server']['port'])")
        g_opts+=( "--port" "$port" );
    fi
}

# ---- main

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

env -i PATH="$g_path" JAVA_HOME="$g_javahome" JAVA_OPTS="-Djava.library.path=" "$g_exe" "${g_opts[@]+${g_opts[@]}}" ${1+"$@"}


