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

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

# ---- globals

rootdir="$g_progdir/../.."
rootdir_abs="$g_progdir_abs/../.."

g_canneddata_dir="$rootdir_abs/bundles/smrtinub/current/private/pacbio/canneddata"
g_pbservice_exe="$rootdir_abs/bundles/smrttools/smrtcmds/bin/pbservice"

g_python3_exe="$rootdir_abs/bundles/smrttools/smrtcmds/bin/python3"
g_serverconfigfile="$rootdir_abs/bundles/smrtlink-analysisservices-gui/current/private/pacbio/smrtlink-analysisservices-gui/smrtlink-system-config.json"

# ---- subroutines

# ---- main

echo "Reading server configuration information..."
host="localhost"
port=$("$g_python3_exe" -c "import json; d = json.load(open('$g_serverconfigfile')); print(d['smrtflow']['server']['port'])")

# Import an example run XML; assumes the canned data have already been
# imported
echo
echo "Importing Example PacBio Sequel Instrument Run"

cmdline="\"$g_pbservice_exe\" import-run \"$g_canneddata_dir/lambdaTINY/r54026_20181219_010102.run.xml\" --reserved --host \"$host\" --port \"$port\""
echo "  Executing: $cmdline"
stat=0
eval "$cmdline" || stat=$?

if [[ $stat -eq 0 ]]; then
    echo "Run import successful."
else
    merror "Run import failed with exit code ${stat}"
fi

exit 0;
