#!/bin/sh
#  $Id: gateway_connection.sh 144933 2017-02-08 09:50:25Z justin.carveley@oracle.com $
#  Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved.
#  This software code contains proprietary information
#  and should be treated as confidential.
#
#  Component: Secure Global Desktop Gateway

. "${INSTDIR}/bin/scripts/common"

[ "${trace}" = "x" ] && set -x

usage() {
    echo "
Usage: gateway connection <command> [<command-specific args>]

  Available commands:
  
  list   Lists connections matching some criteria
  
  Use \"gateway connection <command> --help\" to get help on a command.
    "
    exit 1
}

usage_list() {
    echo "
gateway connection list [--server <host>] [--client <ip>] 
                        [--type http|aip|websocket] 
                        [[--format text|xml|delimited] [--delimiter <delim>]]

  Lists connections matching the specified criteria.

  --server <host>               Server hostname
  --client <ip>                 Client IP address
  --type http|aip|websocket     Type of connection
  --format text|xml|delimited   Output format (default: text)
  --delimiter <delim>           Delimiter used with delimited output format
    "
    exit 1
}

GetSGDServers() {
    # Note: This keytool code is repeated and should be placed in common
    # location which can be shared by the scripts.
    # The keytool command can be used without the password specified as
    # an argument to list the keystore contents. When used this way,
    # keytool asks for a password which can be answered with a carriage
    # return. The keytool will still present the results but displays a
    # warning message which is sent to /dev/null
    LANG=C LC_ALL=C ${GW_JAVA_DIR}/keytool \
	-list -v \
	-keystore "${INSTDIR}/proxy/etc/keystore" << EOF 2> /dev/null |
EOF
    while read data; do
	case "${data}" in
	    Alias*[nN]ame:*)
                alias=`expr "${data}" : 'Alias[^:]*: *\(.*\)'`
		;;
	    Entry*[tT]ype:*)
                type=`expr "${data}" : 'Entry[^:]*: *\(.*\)'`
		[ "${type}" = "trustedCertEntry" ] && echo "${alias}"
		;;
        esac
    done |
    LANG=C LC_ALL=C sort -u |
    while read alias; do
       case "${alias}" in
         *-ssl)
            # ignore the ssl certs
            ;;
         *)
            echo ${alias}
            ;;
       esac
    done
}

QueryProxy() {
    EMPTY=`grep empty ${INSTDIR}/etc/reflection-ssl.xml`
    [ -n "${EMPTY}" ] && {
      # The reflection service is not enabled
      echo "You must enable the reflection service to use this command. This can 
be activated via

gateway config enable --services-reflection-auth"
      exit 1
    } 

    SGDSERVERS=`GetSGDServers|tr '\012' ' '`

    SERVER="" CLIENT="" TYPE="" TIME_START="" TIME_END="" XML="" DELIMITED="" DELIMITER=""
    while [ -n "$1" ]; do
    case "$1" in
    --server)
        case "$2" in
            "" | --*) printf "${i18n_invalidarg01_gw}" "$1"; usage_list
        esac
        SERVER="$2"
        shift
        ;;
    --client)
        case "$2" in
            "" | --*) printf "${i18n_invalidarg01_gw}" "$1"; usage_list
        esac
        CLIENT="$2"
        shift
        ;;
    --type)
        case "$2" in
            http) TYPE="HTTP";;
            aip)  TYPE="TCC";;
            websocket) TYPE="WS";;
            *) printf "${i18n_invalidarg01_gw}" "$1"; usage_list;;
        esac
        shift
        ;;
    --time)
        case "$2" in
            "" | --*) printf "${i18n_invalidarg01_gw}" "$1"; usage_list
        esac
        case "$3" in
            "" | --*) printf "${i18n_invalidarg01_gw}" "$1"; usage_list
        esac
        TIME_START="$2" TIME_END="$3"
        shift; shift
        ;;
    --format)
        case "$2" in
            xml) XML="true";;
            delimited) DELIMITED="true";;
            text) ;;
            *) printf "${i18n_invalidarg01_gw}" "$1"; usage_list;;
        esac
        shift
        ;;
    --delimiter)
        case "$2" in
            "" | --*) printf "${i18n_invalidarg01_gw}" "$1"; usage_list
        esac
        DELIMITER="$2"
        shift
        ;;
    --help)
        usage_list
        exit 1
        ;;
    *) usage_list
    esac
    shift
    done

    # Build the command line for the Java code
    CMDLINE=""
    [ -n "${SERVER}" ] && {
        CMDLINE="${CMDLINE} -server ${SERVER}"
    }
    
    [ -n "${CLIENT}" ] && {
        CMDLINE="${CMDLINE} -client ${CLIENT}"
    }

    [ -n "${TYPE}" ] && {
        CMDLINE="${CMDLINE} -type ${TYPE}"
    }

    [ -n "${TIMESTART}" ] && {
        CMDLINE="${CMDLINE} -time \"${TIME_START}\" \"${TIME_END}\""
    }

    [ -z "${CMDLINE}" ] && {
        # No arguments so display all connections
        CMDLINE="${CMDLINE} -all" 
    }
 
    # Add format arguments
    [ -n "${XML}" ] && {
        CMDLINE="${CMDLINE} -xml"
    }

    [ -n "${DELIMITED}" -a -n "${DELIMITER}" ] && {
        CMDLINE="${CMDLINE} -delimiter ${DELIMITER}"
    }

    # Execute the request
    KEYSTORE_PASSWD=`cat ${INSTDIR}/etc/password.reflection`
    HOST=`sed 's/\(.*\):/\1 /' < ${INSTDIR}/etc/reflection-auth-binding.xml | tr '<' ' ' | tr '>' ' ' | awk '{ print $2 }'`
    PORT=`sed 's/\(.*\):/\1 /' < ${INSTDIR}/etc/reflection-auth-binding.xml | tr '<' ' ' | tr '>' ' ' | awk '{ print $3 }'`
    [ "${HOST}" = '*' ] && HOST="localhost"
    ID_MAPPINGS="${INSTDIR}/etc/serveridmap.properties"

    JAVA_ARGS="-classpath ${INSTDIR}/proxy/jarp.jar \
        -Djavax.net.ssl.trustStore=${INSTDIR}/proxy/etc/keystore.reflection \
        -Djavax.net.ssl.trustStorePassword=${KEYSTORE_PASSWD} \
        -Djavax.net.ssl.keyStore=${INSTDIR}/proxy/etc/keystore.reflection \
        -Djavax.net.ssl.keyStorePassword=${KEYSTORE_PASSWD} \
        -DserverId.mapping.file="${ID_MAPPINGS}" \
        proxy.output.GatewayStatus ${HOST} ${PORT}"

    ${GW_JAVA_DIR}/java ${JAVA_ARGS} "${SGDSERVERS}" ${CMDLINE}
}

. ${INSTDIR}/etc/version

apachepath="${INSTDIR}/httpd/httpd-${VERSION_APACHE}"
apachebin=$apachepath/bin/apachectl
apacheconf=$apachepath/conf/httpd.conf
fApachePid="${apachepath}/logs/httpd.pid"
fProxyPid="${INSTDIR}/proxy/var/run/proxy.pid"

GetApachePid() {
    _pid=""
    [ -s "${fApachePid}" ] && _pid=`tr -cd '0123456789' <"${fApachePid}"`
    [ -n "${_pid}" ] && [ -n "`ps -p${_pid} | grep \"${_pid}\"`" ] && echo "${_pid}"
    return 0
}

GetProxyPid() {
    _pid=""
    [ -s "${fProxyPid}" ] && _pid=`tr -cd '0123456789' <"${fProxyPid}"`
    [ -n "${_pid}" ] && [ -n "`ps -p${_pid} | grep \"${_pid}.*java\"`" ] && echo "${_pid}"
    return 0
}


# Check for --help 
if [ "$1" = "--help" ]; then
    usage
elif [ "$1" = "list" -a "$2" = "--help" ]; then
    usage_list
elif [ -z "$1" ]; then
    usage
fi

ApachePid=`GetApachePid`
ProxyPid=`GetProxyPid`

if [ -n "${ApachePid}" -a -z "${ProxyPid}" ]; then
    # Apache running, Proxy not
    printf "${i18n_statusstrange11_gw}" "${INSTDIR}"
elif [ -z "${ApachePid}" -a -n "${ProxyPid}" ]; then
    # Proxy running, Apache not
    printf "${i18n_statusstrange11_gw}" "${INSTDIR}"
elif [ -n "${ApachePid}" -a -n "${ProxyPid}" ]; then
    case "$1" in
    list)
        shift
        QueryProxy "$@"
        ;;  
    *)  
        usage
        ;;
    esac
else
    # neither Proxy nor Apache running
    echo "Couldn't list the connections."
fi

exit 0
