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

# this only has two subdirectories, "canneddata" and "barcodes"
g_canneddata_dir="$rootdir_abs/bundles/smrtinub/current/private/pacbio"

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'])")

# Check to make sure the services are available
echo
echo "Checking server status with 'pbservice status'..."
cmdline="\"$g_pbservice_exe\" status --log-level DEBUG --host \"$host\" --port \"$port\""
echo "  Executing: $cmdline"
stat=0;
eval "$cmdline" || stat=$?
if [[ $stat -ne 0 ]] ; then
    merror "Services are not running properly."
fi


echo
echo "Importing canned data and barcodes..."

cmdline="\"$g_pbservice_exe\" import-dataset --log-level DEBUG --host \"$host\" --port \"$port\" \"$g_canneddata_dir\""
echo "  Executing: $cmdline"
eval "$cmdline" || stat=$?
if [[ $stat -ne 0 ]] ; then
    merror "Running import-dataset for canned data failed."
fi

exit 0
