#!/bin/bash -e
# -*- 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

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

# ---- global env

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

SMRT_ROOT="${g_progdir_abs}/../.."

getstatus_exe="$SMRT_ROOT/bundles/smrtlink-analysisservices-gui/current/private/pacbio/smrtlink-analysisservices-gui/bin/get-status"
java_home="$SMRT_ROOT/bundles/smrtlink-analysisservices-gui/current/private/thirdparty/java/jre/jre_8u192b12-hotspot"

echo "Checking WSO2 API Manager is stopped..."

# Use get-status to determine if we can connect to a wso2 URL.  This does not
# check to see if the wso2 process is running, just if we can connect.  We
# will assume it is not running if we cannot connect.
# Redirect stdout and stderr to /dev/null and rely only on the exit status
stat=0
JAVA_HOME="$java_home" JAVA_OPTS="-Djava.library.path=" "$getstatus_exe" --subcomponent-id wso2 > /dev/null 2>&1 || stat=$?

wso2running=false;
if [[ $stat -eq 0 ]] ; then
    wso2running=true;
fi

if $wso2running; then
    echo "  WSO2 API Manager is currently running."
    echo 2>&1
    echo "ERROR! WSO2 must be stopped before installing SSL certificate." 1>&2
    echo "       Run '$g_progdir/services-stop' to stop all services." 1>&2
    exit 1;
else
    echo "  WSO2 API Manager is currently stopped."
fi

echo
echo "Installing SSL certificate..."
# Specify path to our keytool in the jre bin directory
stat=0;
PATH="$java_home/bin:$PATH" \
    "$SMRT_ROOT/bundles/smrtlink-analysisservices-gui/current/private/pacbio/smrtlink-analysisservices-gui/bin/install-ssl-cert" "$@" || stat=$?

if [[ $stat -ne 0 ]] ; then
    echo "  ERROR!  Error detected in SSL certificate install." 1>&2
    exit $?
fi
echo "  SSL certificate installed successfully."
exit 0;
