#!/bin/sh

# Copyright (c) 2015 Ericsson AB.
# All rights reserved.

# The script enables a number of com process management capabilities.
print_usage() {
cat << EOT
Usage:
        com.sh [-d secs] [-e] <start|restart>
        com.sh <stop>

        -d secs: startup delay; has no effect on stop operation
        -e:      start environment SNMP adapter (always stopped on COM stop)
EOT
}

# default startup delay
delay=0

# do not start SNMP environment adapter by default
comea=""

# option(s)
while getopts ed: option
do
    case $option in
        e)       comea="start";;

        d)       delay="$OPTARG"
                 expr 1 + "$delay" >/dev/null || {
                     print_usage >&2
                     exit 1
                 };;

        \?)      print_usage >&2
                 exit 1;;
    esac
done
shift `expr $OPTIND - 1`

COM_CMD="/opt/com/bin/com"
COM_ENV_FLAG="/opt/com/com.env"
CFG_NAME="com.cfg"

if [ -e ${COM_ENV_FLAG} ]; then
    COM_CONF=`cat ${COM_ENV_FLAG}`/etc/${CFG_NAME}
else
    COM_CONF="/opt/com/etc/${CFG_NAME}"
fi

# COM environment
test -r /opt/com/bin/com_env && . /opt/com/bin/com_env

create_libcrypto_symlink() {
   # the way open-SSL lib needs to be seen on PCREF platform
   COM_LIBCRYPTO6="/usr/lib/libcrypto.so.6"
   COM_LIBCRYPTO9=`/bin/ls /lib/libcrypto.so.0.9* 2>/dev/null | tail -1`

   if [ "x${COM_LIBCRYPTO9}" != x ]; then       #safer and  more portable than -n
      if [ -f "${COM_LIBCRYPTO9}" -a ! -L "${COM_LIBCRYPTO6}" ]; then
         # create if not available
         /bin/ln -sf "${COM_LIBCRYPTO9}" "${COM_LIBCRYPTO6}"
      fi
   else
      unset NETSNMP_ROOT
      echo "Skipping symlink creation for ${COM_LIBCRYPTO6}"
   fi
}

create_maf_symlink() {
   COM_MAF="/opt/com/bin/maf"

   if [ -f "${COM_MAF}" ]; then
      # create if available
      /bin/rm "${COM_CMD}"
      /bin/ln -sf "${COM_MAF}" "${COM_CMD}"
   fi
}

LOG_DIR=/var/log
LOG_FILE_MAXCOUNT="1"
LOG_FILE_MAXSIZE="10000000"
LOG_FILE="${LOG_DIR}/com.log"
STDOUT_FILE="/dev/null"
TMP_DIR="/tmp"
COMEA="/opt/com/comea/bin/comea"
START_UNICLI_FLAG="/flash/uni_cli_default"
START_EXECCLI_FLAG="/flash/exec_cli_default"

PID_FILE=/opt/com/run/com.pid

# test for execution comea and it's dependencies
test -x /opt/com/comea/bin/comea || {
    echo "Note: SNMP environment adapter not installed.." >&2

    # do not try to start it later on
    comea=""
}

# adding comea and start-stop-daemon to the system path
export PATH=/opt/com/comea/bin:/sbin:${PATH}

comea_start() {
    if [ -x "$COMEA" ]; then
        echo "Starting COM External Agent"
        "$COMEA" snmp start
    else
        echo "Not starting COM External Agent (not installed)" >&2
    fi
}

createLog(){
    if [ ! -d `dirname ${LOG_FILE}` ]; then
        error "COM log dir not found: ${LOG_FILE}"
        return
    fi

    if [ ! -f ${LOG_FILE} ]; then
        touch ${LOG_FILE}
    fi

    chmod a+r ${LOG_FILE}
}

# sets the default cli
# if ${START_UNICLI_FLAG} exists, unicli is set as the default
# if ${START_EXECCLI_FLAG} exists, exec_cli is set as the default
# if none of the files exist, the active cli is not changed
switch_cli() {
    if [ -e ${START_UNICLI_FLAG} ]; then
        if [ `readlink /opt/ipos/bin/exec_cli` = "/opt/ipos/bin/exec_cli_legacy" ]; then
            echo "com.sh: Setting unicli as default"
            ln -sf /opt/ipos/bin/uni_cli /opt/ipos/bin/exec_cli
            ln -sf /opt/com/unicli/cliss /opt/com/bin/cliss
            ln -sf /opt/com/unicli/libcom_cli_agent.so /opt/com/lib/comp/libcom_cli_agent.so
            ln -sf /opt/com/unicli/libcom_cli_agent.cfg /opt/com/lib/comp/libcom_cli_agent.cfg
        fi
    else
        if [ -e ${START_EXECCLI_FLAG} ]; then
            if [ `readlink /opt/ipos/bin/exec_cli` = "/opt/ipos/bin/uni_cli" ]; then
                echo "com.sh: Setting exec_cli as default"
                ln -sf /opt/ipos/bin/exec_cli_legacy /opt/ipos/bin/exec_cli
                ln -sf /opt/com/ipcli/cliss /opt/com/bin/cliss
                ln -sf /opt/com/ipcli/libcom_cli_agent.so /opt/com/lib/comp/libcom_cli_agent.so
                ln -sf /opt/com/ipcli/libcom_cli_agent.cfg /opt/com/lib/comp/libcom_cli_agent.cfg
            fi
        fi
    fi
}

start() {
    switch_cli
    sleep $delay

    ulimit -c unlimited
    # Default log level
    export MAF_LOGGING_LEVEL="6" # Trace logs
    export COM_LOGGING_LEVEL="6" # Trace logs

    createLog

    # Will contain logs from com startup before the log and trace spi
    # are available
    export MAF_LOGGING_FMAXSIZE=${LOG_FILE_MAXSIZE}
    export MAF_LOGGING_FNAME=${LOG_FILE}
    export COM_LOGGING_FMAXCOUNT=${LOG_FILE_MAXCOUNT}
    export COM_LOGGING_FMAXSIZE=${LOG_FILE_MAXSIZE}
    export COM_LOGGING_FNAME=${LOG_FILE}
    export TMPDIR=${TMP_DIR}

    create_maf_symlink           #create symlink for maf/com
    create_libcrypto_symlink           #create symlink if not exist
    echo "[`date +%Y-%m-%d_%H.%M.%S`] - COM - Start."

    if [ "$comea" ]; then
        # start external agent only on successful COM startup
        if [ 0 -eq $EXIT_CODE ]; then
            comea_start
            EXIT_CODE=$?
        else
            echo "Not starting COM External Agent (unsuccessful COM startup)" >&2
        fi
    fi

    echo $$ > ${PID_FILE}
    exec ${COM_CMD} ${COM_CONF} >> ${STDOUT_FILE} 2>&1
    EXIT_CODE=$?

    exit $EXIT_CODE
}

comea_stop() {
    if [ -x "$COMEA" ]; then
        echo "Stopping COM External Agent"
        "$COMEA" terminate
    else
        echo "Not stopping COM External Agent (not installed)" >&2
    fi
}

stop() {
    # stop the external agent
    comea_stop

    echo "[`date +%Y-%m-%d_%H.%M.%S`] - COM - Stop."
    kill -15 `cat $PID_FILE` >/dev/null 2>&1 || true

    # FIXME ekasske: This does screw-up restart.. It will exit before start!
    # Is there any reason why there is exit 0 here?
    exit 0
}

case "$1" in
    start)
        start
        ;;

    stop)
        stop
        ;;

    restart)
        stop
        start
        ;;
    *)
        echo "Invalid command: $0 $*"
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit 0
