#!/bin/bash
# Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Restart SGD services
#

# This is a generic product script used to establish an environment
# before starting/stopping a product or component.
# This script was built from shell library
#   $Id$
# This script has to run on every platform we support.  Any suggestions
# for improvement are welcome (but must be portable!)

# Version numbers
PRODUCT_VERSION="5.60.514"
PRODUCT_VERSION_FULL="5.60.514"
PRODUCT_VERSION_MAJOR=5
PRODUCT_VERSION_FEATURE=6
PRODUCT_VERSION_BUG=0
PRODUCT_VERSION_BUILD=514
PRODUCT_VERSION_BUILD_DECIMAL=514
PRODUCT_VERSION_AS_NUMBER=560514
PRODUCT_VERSION_CAB=5,6,0,514
PRODUCT_VERSION_RPM=5.60-514

# Product names
PRODUCT_FULL_NAME="Oracle Secure Global Desktop"
PRODUCT_SHORT_NAME="Secure Global Desktop"
PRODUCT_IDENT="SSGD"
PRODUCT_SHORT_FILENAME="Tarantella"
PRODUCT_LSBSCRIPTNAME="sun.com-sgd-base"
PRODUCT_LSBSCRIPT_RUN_LEVEL="90"
TSP_FULL_NAME="Oracle Secure Global Desktop Security Pack"
TSP_SHORT_NAME="Security Pack"
WCP_FULL_NAME="Oracle Secure Global Desktop Windows Connectivity Pack"
WCP_SHORT_NAME="Windows Connectivity Pack"
TN3270_FULL_NAME="Oracle Secure Global Desktop Mainframe Connectivity Pack"
TN3270_SHORT_NAME="Mainframe Connectivity Pack"
AS400_FULL_NAME="Oracle Secure Global Desktop AS/400 Connectivity Pack"
AS400_SHORT_NAME="AS/400 Connectivity Pack"
S1PSTK_FULL_NAME="Oracle Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_FULL_NAME="Oracle Secure Global Desktop Integration Pack for Sun ONE Portal Server"
S1PSTK_SHORT_NAME="Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_SHORT_NAME="Secure Global Desktop Integration Pack for Sun ONE Portal Server"

OBJECT_MGR_NAME="Object Manager"
ARRAY_MGR_NAME="Array Manager"
NATIVE_WIN16_FULL_NAME="Oracle Secure Global Desktop Native Client for Windows 3.1"
NATIVE_WIN16_SHORT_NAME="Native Client for Windows 3.1"
NATIVE_WIN32_FULL_NAME="Oracle Secure Global Desktop Native Client for Windows 95, 98 and NT"
NATIVE_WIN32_SHORT_NAME="Native Client for Windows 95, 98 and NT"
NATIVE_WYSE_FULL_NAME="Oracle Secure Global Desktop Native Client for Wyse"
NATIVE_WYSE_SHORT_NAME="Native Client for Wyse"
NATIVE_FULL_NAME="Oracle Secure Global Desktop Native Client"
NATIVE_SHORT_NAME="Native Client"
NATIVE_REGISTRY_NAME="Tarantella Native Client"
INTCLI_FULL_NAME="Oracle Secure Global Desktop Client"
INTCLI_SHORT_NAME="Client"
TCC_FULL_NAME="Oracle Secure Global Desktop Client"
TCC_HELPER_NAME="Oracle Secure Global Desktop Client Helper"
TCC_ACTIVEX_NAME="Oracle Secure Global Desktop ActiveX Control"
TCC_PLUGIN_NAME="Oracle Secure Global Desktop Netscape Plug-in"
T3COMPONENT_WIN_NAME="Oracle Secure Global Desktop Enhancement Module for Windows"
T3COMPONENT_UNIX_NAME="Oracle Secure Global Desktop Enhancement Module for UNIX(TM) and Linux Platforms"
T3COMPONENT_SHORT_UNIX_NAME="tem"
T3COMPONENT_NAME="Oracle Secure Global Desktop Enhancement Module"
T3COMPONENT_LSBSCRIPTNAME="sun.com-sgd-em"
T3COMPONENT_LSBSCRIPT_RUN_LEVEL="90"
GWCOMPONENT_UNIX_NAME="Oracle Secure Global Desktop Gateway for UNIX(TM) and Linux Platforms"
GWCOMPONENT_NAME="Oracle Secure Global Desktop Gateway"
GWCOMPONENT_SHORTNAME="SGD Gateway"
GWCOMPONENT_LSBSCRIPTNAME="sun.com-sgd-gw"
GWCOMPONENT_LSBSCRIPT_RUN_LEVEL="91"

# Watch the length of these names: IE refuses to remove packages if
# the name is too long.
ARCHIVE_NAME_ttalw="TCC Helper, version"
ARCHIVE_NAME_asad="3.x Framework Java Archive"
#ARCHIVE_NAME_tta="3.x Java Archive"
#ARCHIVE_NAME_tta="3.x Combined Java Archive"
ARCHIVE_NAME_tta="Client, "
ARCHIVE_NAME_tsp="3.x Security Java Archive"
ARCHIVE_NAME_proxy="3.x Proxy Java Archive"
WEBSTART_JAR_NAME="sgdwscs"
ARCHIVE_SUFFIX="K"

NS_REGKEY="java/download/com/tarantella/tta"

PRODUCT_VENDOR="Oracle Corporation, Inc."
PRODUCT_SHORT_VENDOR="Oracle"

# Capabilities:
# The format for the capabilities required by the client end of a
# connection is: CAPABILITIES_protocol_type_REQUIRED="expression"

# The format for the capabilities provided by the server end of a
# connection is: CAPABILITIES_protocol_type_PROVIDED="c1 c2 ... c3"

# Asad between a webtop client and server:
CAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"

# Asad between two peer servers, or an admin tool and a server:
# 1.1 is core E3 array functionality.
# 1.2 is 3.01 array interoperability functionality.
# 2.1 is core Pisa client device mapping functionality (not a requirement)
CAPABILITIES_ASAD_PEER_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_PEER_PROVIDED="1.1 1.2 2.1"

# Client versions of server strings; same format, name prefixed by CLIENT
# Asad between a webtop client and server:
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"

# Top-level item names in ENS datastore
DEFAULT_ROOT_ENS="organization"
SYSTEM_ROOT_ENS="Tarantella System Objects"
APP_ROOT_ENS="applications"
APPSERVER_ROOT_ENS="appservers"

WEB_SERVICES_VERSION=1.9


# be paranoid about the current path
if [ -d /bin ]; then
  PATH=/bin:$PATH
fi
if [ -d /sbin ]; then
  PATH=/sbin:$PATH
fi
if [ -d /usr/bin ]; then
  PATH=/usr/bin:$PATH
fi
if [ -d /usr/sbin ]; then
  PATH=/usr/sbin:$PATH
fi
if [ -d /etc ]; then
  PATH=/etc:$PATH
fi
export PATH

u="`LANG=C LC_ALL=C id | sed 's/.*uid=\([0-9][0-9]*\).*/\1/'`"
if [ "$u" = "0" ]
then
  : # all is okay
else
  echo "You must be root to run this program"
  exit 15
fi

if [ -f $TTAMSG/common -a -f $TTAMSG/tta_restart ]; then
  . $TTAMSG/common
  . $TTAMSG/tta_restart
else
  echo "Unable to open message file: $TTAMSG/tta_restart"
  exit 1
fi

if [ -z "$0" ]; then
  who_i_am=""
else
  who_i_am=`expr "//$0" : '.*/\(.*\)' `
fi


case "$trace" in x|X) set -x;; esac


### Constants ###

SUBSVC_SGD=sgd
SUBSVC_CDM=cdm
SUBSVC_WEBSERVER=webserver

EXIT_SUCCESS=0
EXIT_INVALID_USAGE=1

STOP_EXIT_SUCCESS=0
STOP_EXIT_PROMPT_REJECTED=2



### Local Functions ###

# $1 - exit code
function ExitUsage()
{
    echo "${lf_usage}" 1>&2
    exit $1
}


function ExitInvalidUsage()
{
    echo "${l_invalid_arg1}$1${l_invalid_arg2}" 1>&2
    echo "${sf_usage}" 1>&2
    exit ${EXIT_INVALID_USAGE}
}


# Parse and validate the command line arguments.
# Accepted syntaxes:
#     1) tarantella restart [--force] [--yes]
#     2) tarantella restart --live
#     2) tarantella restart --help
# Deprecated syntaxes:
#     3) tarantella restart [--warm | --kill] [--quiet] [--http | --https]
#                           [--servlet]
#     4) tarantella restart sgd [--warm | --kill] [--quiet]
#     5) tarantella restart webserver [--http | --https] [--servlet]
#
# Input parameters:
#     $@ - Command line parameters.
# Output globals:
#     opt_subservice  the subservice to restart (sgd, webserver) [deprecated] or#                     empty (both)
#     opt_help        true iff --help is specified
#     opt_live        true iff --live is specified
#     opt_force       true iff --force is specified
#     opt_yes         true iff --yes is specified
#     opt_warm        true iff --warm is specified [deprecated]
#     opt_kill        true iff --kill is specified [deprecated]
#     opt_quiet       true iff --quiet is specifed [deprecated]
#     opt_http        "--http" iff --http specified, else empty [deprecated]
#     opt_https       "--https" iff --https specified, else empty [deprecated]
#     opt_servlet     "--servlet" iff --servlet specified, else empty
#                     [deprecated]
#
# Returns: An exit code
#     EXIT_SUCCESS              on success
#     EXIT_INVALID_USAGE        if a syntax error is encountered
#
function ParseOptions()
{
    opt_subservice=
    opt_help=false
    opt_live=false
    opt_force=false
    opt_yes=false
    opt_warm=false
    opt_kill=false
    opt_quiet=false
    opt_http=
    opt_https=
    opt_servlet=

    case "$1" in
        # all subservice are deprecated
        ${SUBSVC_SGD}|${SUBSVC_WEBSERVER})
            opt_subservice="$1"
            shift
            ;;
    esac

    local http_or_https=
    while [ $# -gt 0 ]
    do
        case "$1" in
            --help)
                opt_help=true
                return $EXIT_SUCCESS
                ;;
            --live)
                opt_live=true
                ;;
            --force)
                opt_force=true
                ;;
            --kill)
                opt_kill=true
                ;;
            --yes)
                opt_yes=true
                ;;
            --warm)
                opt_warm=true
                ;;
            --quiet)
                opt_quiet=true
                ;;
            --http)
                opt_http="$1"
                ;;
            --https)
                opt_https="$1"
                ;;
            --servlet)
                opt_servlet="$1"
                ;;
            *)
                return $EXIT_INVALID_USAGE
                ;;
        esac
        shift
    done

    local have_webopt=false
    [ -n "${opt_http}" -o -n "${opt_https}" -o -n "${opt_servlet}" ] &&
       have_webopt=true

    # --http, --https, --servlet are only valid if starting the webserver
    ${have_webopt} &&
        [ -n "${opt_subservice}" -a \
          "${opt_subservice}" != ${SUBSVC_WEBSERVER} ] &&
            return ${EXIT_INVALID_USAGE}

    # --http and --https are mutually exclusive
    [ -n "${opt_http}" -a -n "${opt_https}" ] && return ${EXIT_INVALID_USAGE}

    # --force can't be used with --live or webserver subservice
    ${opt_force} && ${opt_live} &&
        return ${EXIT_INVALID_USAGE}
    ${opt_force} && [ "${opt_subservice}" = ${SUBSVC_WEBSERVER} ] &&
        return ${EXIT_INVALID_USAGE}

    # --yes can only be used in the 1st non-deprecated form without a subservice
    ${opt_yes} && [ -n "${opt_subservice}" ] && return ${EXIT_INVALID_USAGE}
    ${opt_yes} && ${have_webopt} && return ${EXIT_INVALID_USAGE}
    ${opt_yes} && ${opt_warm} && return ${EXIT_INVALID_USAGE}
    ${opt_yes} && ${opt_live} && return ${EXIT_INVALID_USAGE}

    # --warm and --kill can only be used in the deprecated form when the sgd
    # subservice or no subservice is specified
    (${opt_warm} || ${opt_kill}) && ${opt_live} && return ${EXIT_INVALID_USAGE}
    (${opt_warm} || ${opt_kill}) && ${opt_yes} && return ${EXIT_INVALID_USAGE}
    (${opt_warm} || ${opt_kill}) &&
        [ -n "${opt_subservice}" -a "${opt_subservice}" != ${SUBSVC_SGD} ] &&
            return ${EXIT_INVALID_USAGE}

    return $EXIT_SUCCESS
}


# Live restart.
# Send SIGUSR1 to live-updatable processes.
# If the processes are not running, has no effect.
# Input globals:
#     TTAINSTDIR  The SGD install path.
function LiveRestart()
{
    # Live restart of supported PEs
    AUXSERVERPIDFILE="${TTAINSTDIR}/var/info/auxserver.pid"
    [ -r "${AUXSERVERPIDFILE}" ] &&
        kill -s SIGUSR1 $(cat "${AUXSERVERPIDFILE}") > /dev/null 2>&1 &&
           echo "${restarted_live}"

    # Live restart of apache webserver
    WEBSERVERDIR="${TTAINSTDIR}/webserver"
    APACHEDIR="${WEBSERVERDIR}/apache"
    APACHEVERSION="${TTAINSTDIR}/var/info/apacheversion"
    APACHEPATH="${APACHEDIR}/$(cat ${APACHEVERSION})"
    if [ -f "${APACHEPATH}/logs/httpd.pid" ]
    then
        . "${APACHEPATH}/bin/envvars"
        # requires the REST_PORT env setting
        REST_PORT="`$TTAINSTDIR/bin/scripts/getconfig --tarantella.config.rest.apiport`" \
            "${APACHEPATH}/bin/apachectl" -d "${APACHEPATH}" -k graceful
    fi
}


# Performs a so-called warm restart of the Jserver.
# Input globals:
#     TTADIR      The SGD install path.
#     TTADATADIR  The data subdirectory in the SGD install.
function DeprecatedWarmRestart()
{
    # Old so-called warm restart. Terminates client connections.
    ${TTADIR}/bin/tarantella stop --restart --quiet
    if [ $? -eq ${STOP_EXIT_SUCCESS} ]
    then
        echo "$restarted_warm_req"
        exit 0
    fi
    pid=0
    for p in `cat ${TTADATADIR}/info/auxserver.pid 2>/dev/null`
    do
        kill -USR1 $p 2>/dev/null && pid=$p
    done
    if [ $pid -ne 0 ]
    then
        echo "$restarted_warm_force"
        exit 0
    fi
    # Couldn't find a process to signal.
}


# Cold restart.
# Input globals:
#     opt_yes
#     opt_force
#     opt_kill
#     opt_quiet
#     opt_subservice
#     opt_http
#     opt_https
#     opt_servlet
function ColdRestart()
{
    ${opt_yes} &&   stop_opt_yes="--yes"
    ${opt_force} && stop_opt_force="--force"
    ${opt_kill} &&  stop_opt_kill="--kill"
    ${opt_quiet} && stop_opt_quiet="--quiet"
    local stop_opt_subservice="${opt_subservice}"
    local stop_opts_webserver="${opt_http} ${opt_https} ${opt_servlet}"
    ${TTADIR}/bin/tarantella stop \
                             ${stop_opt_subservice} \
                             ${stop_opt_yes} \
                             ${stop_opt_force} \
                             ${stop_opt_kill} \
                             ${stop_opt_quiet} \
                             ${stop_opts_webserver}
    local stop_ret=$?

    if [ ${stop_ret} -eq ${STOP_EXIT_SUCCESS} ]
    then
        local start_opt_subservice="${opt_subservice}"
        local start_opts_webserver="${stop_opts_webserver}"
        exec ${TTADIR}/bin/tarantella start \
                                      ${start_opt_subservice} \
                                      ${start_opts_webserver}
    elif [ ${stop_ret} -ne ${STOP_EXIT_PROMPT_REJECTED} ]
    then
        echo "${restart_stop_failed}"
    fi
}



### Main ###

# Process comannd line options
ParseOptions "$@" || ExitInvalidUsage
${opt_help} && ExitUsage ${EXIT_SUCCESS}

if ${opt_live}
then
    LiveRestart
    exit ${EXIT_SUCCESS}
fi

if ${opt_warm}
then
    DeprecatedWarmRestart
    # Fall through to a normal restart.
    # Note that this allows combinations with other options.
fi

# Full cold restart - stop/start processes
ColdRestart
 
exit 0

