#!/bin/ksh

##############################################################################
#
# Filename         - $Workfile:   archive_monitor.ksh  $
#
# Author           - Dave Banks
#
# Project Name     - UltraTrak Core
#
# Source Code
# Identifier       - Database (Master Standby)
#
# Design Spec
# Section          -
#
# Contents         - Script to monitor the state of the node for archive
#
# Language         - Unix Shell Script (ksh)
#
# Classification   - Commercial In Confidence
#
#          (c) Ultra Electronics Limited, 2006
#
##############################################################################

# Specifiy directory where all archive scripts will be run from
BIN_DIR=${TRAK_BIN}

LOG_FILE=${TRAK_HOME}/log/archive.log
echo "Archive monitor - `date` - activated" >>${LOG_FILE}
while sleep 1
do
    # Check whether the database subsystem is running on this node

    DB_RUNNING=`ps -eaf | grep db7305 | grep -v grep | awk '{print $2}'`

    if [ "${DB_RUNNING}" != "" ]
    then
        # Check whether the archive control script is running.
        # If it is not running then activate it

        ARCHIVE_CONTROL=`ps -eaf | grep archive_control.ksh | grep -v grep | awk '{print $2}'`

        if [ "${ARCHIVE_CONTROL}" = "" ]
        then
            # The archive control script is not running so start it
 
            echo "Archive monitor - `date` - Starting archive control" >>${LOG_FILE}
            ${BIN_DIR}/archive_control.ksh P &
        fi
    else
        echo "Archive monitor - `date` - Database subsystem is not running" >>${LOG_FILE}

        # The database subsystem is not running so kill the archive control script if it is running.

        ARCHIVE_CONTROL=`ps -eaf | grep archive_control.ksh | grep -v grep | awk '{print $2}'`
        if [ "${ARCHIVE_CONTROL}" != "" ]
        then
            # It is running so kill it. Create a file to pause FSU so that archive can complete
            # before FSU restarts when the database subsystem returns.

            echo "Archive monitor - `date` - terminating archive control script" >>${LOG_FILE}
            kill -9 ${ARCHIVE_CONTROL}
            touch $APPN_WORKDIR/sby/stop_fsu
        fi

        # Now check whether the application is running. If it is then carry on monitoring
        # waiting for the database subsystem to restart. If it is not running then exit.

        APP_RUNNING=`ps -eaf | grep node5102 | grep -v grep | awk '{print $2}'`

        if [ "${APP_RUNNING}" = "" ]
        then
            echo "Archive monitor - `date` - Application is not running" >>${LOG_FILE}

            # The application is not running. Terminate.

            echo "Archive monitor - `date` - terminating" >>${LOG_FILE}
            exit
        fi
    fi
done

