#!/bin/sh

TARGET_OS=`uname`
ERROR=0

if [ x$TARGET_OS = xSunOS ]; then 
    PATH=/usr/sbin:/usr/bin
    SPS_SERVER=/opt/SUNWn1sps/N1_Service_Provisioning_System_5.2/server/bin/cr_server
    SPS_AGENT=/opt/SUNWn1sps/N1_Service_Provisioning_System/agent/bin/cr_agent
    CACAODIR=/opt/SUNWcacao
    SCS_DB=/opt/SUNWscs/sbin/db_tool.pl
    # Always check that solaris has this directory,
    # otherwise apache will not start
    if [ ! -d /var/run/apache2 ]; then
        mkdir /var/run/apache2
    fi
    # stop/start httpd on solaris
    SCS_HTTPD_STOP='svcadm disable svc:/network/http:apache2'
    SCS_HTTPD_START='svcadm enable svc:/network/http:apache2'
    SCS_HTTPD_CLEAR='svcadm clear svc:/network/http:apache2'
elif [ x$TARGET_OS = xLinux ]; then 
    PATH=/opt/sun/n1gc/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin
    SPS_SERVER=/opt/sun/N1_Service_Provisioning_System_5.2/server/bin/cr_server
    # try to support both versions of sps
    [ ! -f $SPS_SERVER ] &&  {
    SPS_SERVER=/opt/sun/N1_Service_Provisioning_System_5.0/server/bin/cr_server
    }
    SPS_AGENT=/opt/sun/N1_Service_Provisioning_System/agent/bin/cr_agent
    CACAODIR=/opt/sun/cacao
    SCS_DB=/opt/sun/scs/sbin/db_tool.pl
    SCS_HTTPD_STOP='service init.scs-httpd stop'
    SCS_HTTPD_START='service init.scs-httpd start'
fi
# Check this port using netstat to determine if
# the server has been started
SPS_PORT=1130

SMCWEBSERVER=/usr/sbin/smcwebserver

LOG_FILE=/var/tmp/n1sminit.log

PRODUCT_NAME=N1SM

#
# Define a variable to force stop
# even if some components are not installed.
# HDINIT_FORCE=1

exit_err () {
    echo "ERROR: $1"
    echo "ERROR: $1" >>$LOG_FILE
    echo "Please see log file $LOG_FILE for more information"
    ERROR=1
}

waitForSPS () {
    retries=$1;
    i=0;
    
    # debug
    # echo "Waiting for SPS server. Max retries $retries"

    while [ $i -lt $retries ]; do 
        
        # debug
        # echo "SPS port is $SPS_PORT"

        NETSTAT=`netstat -na | grep "$SPS_PORT "`
        if [ $? -eq 0 ]; then
            # debug
            # echo "Found SPS serevr running";
            # found the socket bound.
            return 0;
        else
            # debug
            # echo "Sleeping to wait for SPS server to start (retry $i)";
            sleep 15;
        fi

        i=`expr $i + 1` 
    done

    return 1;
}

check_hdconfig () {

    # Be sure to update the paths if they change

    [ -f /n1gc-setup/.n1gcconfig_run_once ] || {
        echo "$0: Error: $1 failed - need to run n1smconfig first."
        exit 1
    } 

}

check_files () {

    fail=0

    [ -f $SPS_SERVER ] || {
        echo "$0: Error: $1 failed - $PRODUCT_NAME service provisioning component server is not installed"
        fail=1
    }

    [ -f $SPS_AGENT ] || { 
        echo "$0: Error: $1 failed - $PRODUCT_NAME service provisioning component agent is not installed"
        fail=1
    }

    #SCS db
    [ -f $SCS_DB ] || {
        echo "$0: Error: $1 failed - $PRODUCT_NAME OS provisioning component database is not installed"
        fail=1
    }

    # SCS httpd
    #[ -f $SCS_HTTPD ] || {
    #    echo "$0: Error: $1 failed - $PRODUCT_NAME OS provisioning component http server is not installed"
    #    fail=1
    #}

    [ -f $SMCWEBSERVER ] || {
        echo "$0: Error: $1 failed - $PRODUCT_NAME user interface component is not installed" 
        fail=1
    }

    [ -f $CACAODIR/bin/cacaoadm ] || {
        echo "$0: Error: $1 failed - $PRODUCT_NAME service container component is not installed"
        fail=1
    } 

    [ $fail -eq 1 ] && exit 1

}


#
# Start the services.
#

case "$1" in
start)
    echo "========================= start =============================" >>$LOG_FILE
    # Up the level of open file descriptors
    ulimit -n 16384

    if [ -z "$HDINIT_FORCE" ]; then
        check_hdconfig $1 $2
    fi

    # Check files even on force start since missing files will
    # cause failure no matter what.
    check_files $1 $2

    # stop pxe_watchd to prevent hang during scs-db stop 
    /etc/init.d/init.scs-pxe_watchd stop >/dev/null 2>&1

    #
    # Set up shared memory size, since 
    # XXX need to see if we need to modivy /etc/system
    #
    #echo 536870912 > /proc/sys/kernel/shmmax
    #echo 536870912 > /proc/sys/kernel/shmall

    #/etc/init.d/iptables stop

    [ -f $SCS_DB ] && {
        echo "Starting OS provisioning component database...";
        $SCS_DB start >> $LOG_FILE 2>&1 || exit_err "Failed to start OS provisioning component database"
    }
    
    if [ x$TARGET_OS = xSunOS ]; then 
        # Do this on solaris since sometimes after reboot
        # apache httpd is in maintenance state and will not start.
        $SCS_HTTPD_CLEAR >> $LOG_FILE 2>&1 
    fi
    echo "Starting OS provisioning component http server...";
    $SCS_HTTPD_START >> $LOG_FILE 2>&1 || exit_err "Failed to start httpd"
    
    [ -f $SPS_SERVER ] && {
        echo "Starting service provisioning server...";
        su - n1gsps -c "$SPS_SERVER start" >> $LOG_FILE 2>&1 || exit_err "Failed to start SPS server"
        waitForSPS 15
    }
    [ -f $SPS_AGENT ] && {
        echo "Starting service provisioning agent...";
        $SPS_AGENT start >> $LOG_FILE 2>&1
    }
    
    [ -f $SMCWEBSERVER ] && {
        echo "Starting user interface components...";
        $SMCWEBSERVER start >> $LOG_FILE 2>&1 || exit_err "Failed to start UI component" 
    }

    [ -f $CACAODIR/bin/cacaoadm ] && {
        echo "Starting service container...";
        $CACAODIR/bin/cacaoadm start >> $LOG_FILE 2>&1
        if [ $? -eq 1 ] ; then
            if /opt/SUNWcacao/bin/cacaoadm start 2>&1 |grep lock  >/dev/null
            then
                echo "If cacaoadm daemon is running, it is busy executing another command."
                echo "Otherwise remove lock file  /var/opt/SUNWcacao/run/lock  and restart N1SM."
                exit_err "Unable to start Cacao due to lock file at  /var/opt/SUNWcacao/run/lock"

            fi
        fi 
    }

    if [ $ERROR -gt 0 ] ; then
        echo "N1 services NOT started"
        echo "N1 services NOT started" >>$LOG_FILE
        exit 1
    else
        echo "N1 services started"
        echo "N1 services started" >>$LOG_FILE
    fi
    ;;
#
# Stop the services.
#
stop)
    echo "========================= stop =============================" >>$LOG_FILE
    if [ -z "$HDINIT_FORCE" ]; then
        #check_hdconfig $1 $2
        check_files $1 $2
    fi

    # stop pxe_watchd to prevent hang during scs-db stop 
    /etc/init.d/init.scs-pxe_watchd stop >/dev/null 2>&1

    [ -f $CACAODIR/bin/cacaoadm ] && {
        echo "Stopping service container...";
        $CACAODIR/bin/cacaoadm stop >> $LOG_FILE 2>&1 || exit_err "Failed to stop service container"
    }

    [ -f $SCS_DB ] && {
        echo "Stopping OS provisioning component database...";
        echo "Stopping OS provisioning component database..." >> $LOG_FILE
        $SCS_DB stop >> $LOG_FILE 2>&1
    }

    [ ! -z "$SCS_HTTPD_STOP" ] && {
        echo "Stopping OS provisioning component http server...";
        echo "Stopping OS provisioning component http server..." >> $LOG_FILE
        $SCS_HTTPD_STOP >> $LOG_FILE 2>&1
    }

    [ -f $SPS_AGENT ] && {
        echo "Stopping service provisioning agent...";
        # if the agent is already stopped, then
        # invoking it with "stop" parameter again will exit
        # non zero. (Is this a regression since moving 
        # from SPS 4.1 to SPS 5.0?) Check for force here
        # to allow uninstaller to proceed.
        # if [ -z $HDINIT_FORCE ]; then
        #    $SPS_AGENT stop || exit 1
        # else 
        #    $SPS_AGENT stop 
        # fi

        # for now I won't exit after failure and 
        # should probably file an sps bug
        $SPS_AGENT stop >> $LOG_FILE 2>&1
    }
    [ -f $SPS_SERVER ] && {
        echo "Stopping service provisioning server...";
        #su - n1gsps -c "$SPS_SERVER stop" >> $LOG_FILE 2>&1 || exit_err "Failed to stop SPS server" 
        su - n1gsps -c "$SPS_SERVER stop" 2>&1 |tee -a $LOG_FILE |grep "pg_ctl: postmaster does not shut down" >/dev/null
        if [ $? -eq 0 ] ; then
            echo "SPS stop failed. Retrying stop with 'roxdbcmd pgctl stop -m fast' ..." >> $LOG_FILE
            su - n1gsps -c "/opt/sun/N1_Service_Provisioning_System_5.2/server/bin/roxdbcmd pg_ctl stop -m fast" >> $LOG_FILE
        else
            echo "SPS stop succeeded." >> $LOG_FILE
        fi
    }

    [ -f $SMCWEBSERVER ] && { 
        echo "Stopping user interface components...";
        echo "Stopping user interface components..."  >> $LOG_FILE
        $SMCWEBSERVER stop >> $LOG_FILE 2>&1 || exit_err "Failed to stop UI component"
    }

    if [ $ERROR -gt 0 ] ; then
        echo "N1 services might NOT have stopped due to previous error." >>$LOG_FILE
        echo "N1 services might NOT have stopped due to previous error."
        exit 1
    else
        echo "N1 services stopped" >>$LOG_FILE
        echo "N1 services stopped"
    fi
    ;;

status)
    $CACAODIR/bin/cacaoadm status |grep "default instance is not running" >/dev/null
    if [ $? -eq 0 ] ; then
        echo "N1 is stopped"
    else 
        echo "N1 is started"
    fi 
    ;;

*)
    echo "Usage: $0 {start|stop|status}" >&2
    exit 1
    ;;

esac

exit 0
