#!/bin/sh
# cms           Start and Stops Watchpoint Content Management System Services
#
# Authors:      Matthew Kruer <matthew.kruer@ericsson.com>
#
# description:  Ericsson / SA Media Watchpoint CMS Start Up Script
# processname:  org.jacorb.naming.NameServer (java)
# processname:  org.jboss.Main (java)
# config:       NONE
# pidfile:      NONE

### BEGIN INIT INFO
# Should-Start: $remote_fs $network
# Required-Start: alerts sshd pgbouncer-9.3
# Provides: cms
# Default-Start: 3 5
# Default-Stop: 0 1 2 6
# Description: Content Management System Server
### END INIT INFO

PRODUCT_HOME=/opt/tandbergtv/cms
ACS_SERVER_HOME=/usr/local/acsserver
JAVA_HOME=/usr/java/default/bin
JSTACK_CMD=$JAVA_HOME/jstack

#define the user under which jboss will run, or use RUNASIS to run as the current user
JBOSSUS=${JBOSSUS:-"nobody"}

if [ "$JBOSSUS" = "RUNASIS" ]; then
    SUBIT=""
else
    SUBIT="su $JBOSSUS -c "
fi

PROGNAME=`basename $0`

#define where jboss is - this is the directory containing directories log, bin, conf etc
JBOSS_HOME=${JBOSS_HOME:-"/opt/tandbergtv/jboss"}

if [ ! -d "$JBOSS_HOME" ]; then
    echo JBOSS_HOME does not exist as a valid directory : $JBOSS_HOME
    exit 1
fi

# Setup the java endorsed dirs
JBOSS_ENDORSED_DIRS="$JBOSS_HOME/lib/endorsed"

#define the classpath for the shutdown class
JBOSSCP=${JBOSSCP:-"$JBOSS_HOME/bin/shutdown.jar"}

# Setup the classpath
JBOSS_BOOT_CLASSPATH="$JBOSS_HOME/bin/run.jar"
JBOSS_CLASSPATH="$JBOSS_BOOT_CLASSPATH:$PRODUCT_HOME/workflow/lib:/usr/local/platform/lib/SignatureVerifier.jar"

# Setup properties
JAVA_OPTS="$JAVA_OPTS -Dprogram.name=$PROGNAME -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=10008 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
JAVA_OPTS="$JAVA_OPTS -Dcom.tandbergtv.cms.product.dir=$PRODUCT_HOME -Xmx4096m -XX:+HeapDumpOnOutOfMemoryError -XX:MaxPermSize=512m -XX:StackShadowPages=20 -XX:+UseG1GC -Dcom.tandbergtv.workflow.message.origin=true"
#JAVA_OPTS="$JAVA_OPTS -verbose:gc -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -Xloggc:/opt/tandbergtv/jboss/server/standard/log/GC_`date '+%y%m%d_%H%M%S'`.log"
JAVA_OPTS="$JAVA_OPTS -Dhibernate.dialect=org.hibernate.dialect.PostgreSQLDialect"
JAVA_OPTS="$JAVA_OPTS -Dnetworkaddress.cache.ttl=0 -Dnetworkaddress.cache.negative.ttl=0"

update_cmd_variables() {
    CMD_START="java -server $JAVA_OPTS -Djava.endorsed.dirs="$JBOSS_ENDORSED_DIRS" -classpath "$JBOSS_CLASSPATH" org.jboss.Main "$1" --configuration=standard -b 0.0.0.0"
    CMD_STOP="java -server -classpath $JBOSSCP org.jboss.Shutdown --shutdown"
}

# Checks to see if the license key is installed
licensekey_check() 
{
    if [[ -f "/opt/tandbergtv/cms/conf/workflow/license.xml" ]]; then
        true        
    else 
        printf "  CMS license.xml not found; Aborting start up of CMS\n"
        exit 1
    fi
}

# If cms see that huge pages are set then run cms with hugepages, else disable and warn
hugepages_check()
{
    HUGE_PAGES="-XX:+UseLargePages -XX:LargePageSizeInBytes=2m"
#    CHECK=`sysctl -a | awk '/vm.hugetlb_shm_group =/ {print $3}'`
#    if [[ $CHECK -lt 99 ]]; then
#        printf "  Warning: sysctl vm.hugetlb_shm_group is set to $CHECK, less then the recommended setting of 99 \n"
#        HUGE_PAGES=""
#    fi
#    CHECK=`sysctl -a | awk '/vm.nr_hugepages =/ {print $3}'`
#    if [[ $CHECK -lt 2048 ]]; then 
#        printf "  Warning: sysctl vm.nr_hugepages is set to $CHECK, less then the recommended setting of 3846 \n"
#        HUGE_PAGES=""
#    fi  
#    CHECK=`sysctl -a | awk '/vm.nr_hugepages_mempolicy =/ {print $3}'`
#    if [[ $CHECK -lt 2048 ]]; then 
#        printf "  Warning: sysctl vm.nr_hugepages_mempolicy is set to $CHECK, less then the recommended setting of 3846 \n"
#        HUGE_PAGES=""
#    fi  
#    CHECK=`sysctl -a | awk '/kernel.shmmax =/ {print $3}'`
#    if [[ $CHECK -lt 68719476736 ]]; then
#        printf "  Warning: sysctl vm.hugetlb_shm_group is set to $CHECK, less then the recommended setting of 68719476736 \n"
#        HUGE_PAGES=""
#    fi
    JAVA_OPTS="$JAVA_OPTS $HUGE_PAGES"
}

# Checks to see if alerts services are running
alerts_check() 
{
    nameserver_pid=$(ps axww | grep "[o]rg.openorb.ins.Server" | sed -e 's/^\s*//' | cut -d' ' -f1)
    settingsserver_pid=$(ps axww | grep "[c]om.n2bb.SSModule.SettingsServer" | sed -e 's/^\s*//' | cut -d' ' -f1)
    alerts_pid=$(ps axww | grep "[c]om.n2bb.AlertsModule.AlertServer" | sed -e 's/^\s*//' | cut -d' ' -f1)
    if [[ -z "${nameserver_pid}" ]] || [[ -z "${settingsserver_pid}" ]] || [[ -z "${alerts_pid}" ]] ; then
        printf "  The required service Alerts has not started; Unable to start Content Management System Services\n"
        exit 1
    fi
}

dbserver_check() 
{
    if [[ -f "/opt/PostgresPlus/9.3AS/bin/psql" ]] ; then
    count=0
    delay=1
    timeout=1800
    dbstate=1
    printf "  Waiting for Database to Start"
    while [[ $count -le $timeout && $dbstate > 0 ]] ; do
        sleep $delay
        `PGPASSWORD='Wf$1234' /opt/PostgresPlus/9.3AS/bin/psql -d ttv -U wfs -h dbserver -c "select now()" >  /dev/null 2>&1`
        dbstate=`echo $?` 
        if [[ $count -ge $timeout && $dbstate > 0 ]]; then
            printf "  Unable to connect to the Database after $timeout Seconds \n"
            exit 1
        elif [[ $? > 0 ]]  ; then
            printf "."
            count=$(( $count + $delay ))
        else
            count=$(( $count + $timeout ))
        fi
    done
    printf "\n"
    else
       printf "  psql missing from appliance, continuing to start cms \n"
    fi
}

stale_db_connections_check()
{
    if [[ -f "/opt/tandbergtv/cms/scripts/dbutils/clean_stale_db_connections.sh" ]] ; then
        printf "  Cleaning Stale Database Connections \n"
        bash /opt/tandbergtv/cms/scripts/dbutils/clean_stale_db_connections.sh /dev/null 2>&1
    else 
       printf "  clean_stale_db_connections.sh missing from appliance, continuing to start cms \n"
    fi   
}

adinameserver() 
{
    if [[ -d "$ACS_SERVER_HOME" ]] ; then #Check if ACSServer is installed
        pid=$(ps axww | grep "[o]rg.jacorb.naming.NameServer" | sed -e 's/^\s*//' | cut -d' ' -f1)
        if [[ -z "${pid}" && "start" = $1 ]] ; then
            printf "  Starting ADI NameServer \n"
            "$ACS_SERVER_HOME/scripts/AdiNameService" $1 >/dev/null 2>&1 &
        elif [[ -n "${pid}" && "stop" = $1 ]] ; then
            printf "  Stopping ADI NameServer"
            "$ACS_SERVER_HOME/scripts/AdiNameService" $1 >/dev/null 2>&1 &
            sleep_dots 3
        elif [[ -n "${pid}" && "status" = $1 ]]; then
            printf "  ADI NameServer (pid "$pid") is running \n"
        elif [[ -z "${pid}" && "status" = $1 ]] || [[ -z "${pid}" && "stop" = $1 ]]; then
            printf "  ADI NameServer is stopped \n"
        else
            exit 1
        fi
    else
        printf "  ADI NameServer Not Installed\n"
    fi
}

cms() 
{
    update_cmd_variables
    pid=$(ps axww | grep "[o]rg.jboss.Main" | sed -e 's/^\s*//' | cut -d' ' -f1)
    if [[ -z "${pid}" && "start" = $1 ]] ; then
        printf "  Starting CMS Service"
        $SUBIT "env LANG=en_US.UTF-8 $CMD_START >/dev/null 2>&1 &"
        sleep_dots 5
    elif [[ -n "${pid}" && "stop" = $1 ]] ; then
        printf "  Stopping CMS Service"
        $SUBIT "$JSTACK_CMD -l $pid" > $PRODUCT_HOME/cms_stackdump.txt
        #$SUBIT "$CMD_STOP >/dev/null 2>&1 &"
        cms_shutdown_check
        cms_shutdown_cleanup
    elif [[ -n "${pid}" && "status" = $1 ]]; then
        printf "  CMS Service (pid "$pid") is running \n"
    elif [[ -z "${pid}" && "status" = $1 ]] || [[ -z "${pid}" && "stop" = $1 ]]; then
        printf "  CMS Service is stopped\n"
    else
        exit 1
    fi
}

cms_shutdown_check() 
{
    count=0
    delay=1
    timeout=3
    while [[ $count -le "$timeout" ]] ; do
        sleep $delay
        pid=$(ps axww | grep "[o]rg.jboss.Main" | sed -e 's/^\s*//' | cut -d' ' -f1)
        if [[ -n "$pid" && $count -ge $timeout ]]; then
            #printf " killing process $pid"
            kill -9 $pid
        elif [[ -n "$pid" ]]  ; then
            printf "."
            count=$(( $count + $delay ))
        else
            count=$(( $count + $timeout ))
        fi
    done
    printf "\n"
}

cms_shutdown_cleanup() 
{
    #printf "  Purging temporary jboss files... This may take a while\n"
    if [[ "$(ls -A $JBOSS_HOME/server/standard/tmp)" ]] ; then
        `find $JBOSS_HOME/server/standard/tmp/* -name '*' -print0 | xargs -0 rm -rf >/dev/null 2>&1 &`
    fi
#    if [[ "$(ls -A $JBOSS_HOME/server/standard/work)" ]] ; then
#        `find $JBOSS_HOME/server/standard/work/* -name '*' -print0 | xargs -0 rm -rf >/dev/null 2>&1 &`
#    fi
    #printf "  Purging temporary jboss files complete.\n"
}

sleep_dots() 
{
    for (( start = 1; start <= $1; start++ )); do
        printf "."
        sleep 1
    done
    printf "\n"
}

case "$1" in
    start)
        printf "Starting Content Management System Services: \n"
        licensekey_check
        hugepages_check
        #alerts_check
        dbserver_check
        #service pgbouncer-9.3 restart
        #stale_db_connections_check
        adinameserver $1
        cms $1
        $0 status
        ;;
    stop)
        printf "Stopping Content Management System Services: \n"
        cms $1
        adinameserver $1
        $0 status
        ;;
    status)
        printf " Status of Content Management System Services: \n"
        adinameserver $1
        cms $1
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    *)
        printf "Usage: $0 ( start | stop | status | restart ) \n"
        exit 1
        ;;
esac
exit 0

