#!/bin/ksh

##############################################################################
#
# Filename         - $Workfile:   archive_control.ksh  $
#
# Author           - Dave Banks
#
# Project Name     - UltraTrak Core
#
# Source Code
# Identifier       - Database (Master Standby)
#
# Design Spec
# Section          -
#
# Contents         - Script to control Master Standby parallel archive
#
# Language         - Unix Shell Script (ksh)
#
# Classification   - Commercial In Confidence
#
#          (c) Ultra Electronics Limited, 2007
#
# The archive control script is responsible for controlling parallel archive
# on the UltraTrak system. Typically the script is activated on the Master 
# node and runs a copy of itself on the Standby node if that node is 
# available. The script works in conjunction with the archive monitor script
# to cater for failures and changeovers etc. when archive is occurring. 
#
# When the script runs on the Master it activates the archive monitor script,    
# activates itself on the Standby if available and then performs the archive.
#
# When the script runs on the Standby, it checks whether an archive is needed 
# and if so performs the archive.
#
# The script takes one optional parameter. 
#
# This parameter is can have the following values:
#      -help - Display help information
#      F     - If running on the Standby force the archive to take place 
#              regardless of the state of archive on the Master node. If this 
#              parameter is set on the Master the archive runs anyway (so 
#              the parameter is effectively ignored).
#      P     - If running on the Master then terminate. If running on the 
#              Standby, wait until FSU starts and then pause it before 
#              performing the archive. When the archive is complete, continue FSU.          
#              This is used when activated as part of the database subsystem by HANS 
#              so that archive can run on the Standby before FSU starts.
#
##############################################################################

############################################################################
#
# f_help         
#
# This function displays help information
#
############################################################################

f_help ()
{
      echo "Usage :"
      echo "         archive_control.ksh        - Run without checking anything"
      echo "         archive_control.ksh -help  - Display this help information"
      echo "         archive_control.ksh F      - If running on the Standby then"
      echo "                                      perform archive without checking"
      echo "                                      the status of the Master node"
      echo "         archive_control.ksh P      - If running on the Master then terminate."
      echo "                                      If running on the Standby, wait"
      echo "                                      until FSU starts and then pause" 
      echo "                                      it before performing the archive. "
      echo "                                      When the archive is complete, "
      echo "                                      continue FSU. This is used when "          
      echo "                                      activated as part of the database"
      echo "                                      subsystem by HANS so that archive can run"
      echo "                                      run on the Standby before FSU starts."
      echo
}

############################################################################
#
# f_initialise
#
# This function initialises the variables used by the script
#
############################################################################

f_initialise ()
{
   # Set up the node number and name of this node

   THIS_NODE_NO=`cat $APPN_CONFIGDIR/node_id_config`
   THIS_NODE=`uname -n`

   # Find out the names of node 1 and node 2

   FIRST_NODE=`echo $APPN_RESOURCE_DB_SERVERS | awk '{print $1}'`
   SECOND_NODE=`echo $APPN_RESOURCE_DB_SERVERS | awk '{print $2}'`

   # Determine the name and number of the other node from the information we have

   if [ ${THIS_NODE} = ${FIRST_NODE} ]
   then
      OTHER_NODE=${SECOND_NODE}
      OTHER_NODE_NO=2
   else
      OTHER_NODE=${FIRST_NODE}
      OTHER_NODE_NO=1
   fi
}

###################################################################
#
# Check the running processes for other archive_control scripts.
# Puts a full process list in a file and greps for this process but
# which do not match on PID, parent PID or time of activation.
#
###################################################################
f_check_ps()
{
   ps -eaf > /tmp/check_ps_$$.ps
   grep ${1} /tmp/check_ps_$$.ps | grep -v ${2} | grep -v ${3} | grep -v ${4}  | grep -v ${REM_SHELL} | grep -v grep
   \rm -f /tmp/check_ps_$$.ps > /dev/null 2>&1
}

############################################################################
#
# f_check_script_running
#
# This function checks whether another copy of the script is already running
# or not. If it is then the script terminates.
#
############################################################################

f_check_script_running ()
{
    #
    # The time passed in is the time we started.
    #
    DT=`echo $1 | cut -b 1-5`

    #
    # Get my own process line ( and log it )
    #
    echo "My PID ..."$$ >> ${LOG_FILE}
    ME=`ps -eaf | grep $0 | grep $$ | grep -v grep`
    echo "I am ..."${ME}" running at "${DT} >> ${LOG_FILE}
    #
    # Get my parent process PID ( and log it )
    #
    MY_PARENT=`echo ${ME} | awk '{print $3}'`
    echo "Parent process is ..."${MY_PARENT} >> ${LOG_FILE}
    echo "------------------------------------------------------------------------------" >> ${LOG_FILE}
    echo "Other instances of parent process " >> ${LOG_FILE}
    ps -eaf | grep ${MY_PARENT} | grep -v grep >> ${LOG_FILE}
    echo "------------------------------------------------------------------------------" >> ${LOG_FILE}
    #
    # Now look for any other instances NOT spawned by the same parent or myself or at the same time
    # Call a function within this script as executing the command directly here seems to be unreliable.
    #
    CMD=`f_check_ps ${0} ${MY_PARENT} $$ ${DT}`
    if [ "${CMD}" = "" ]
    then
       echo "Archive control - `date` - This is the only copy of the script" >>${LOG_FILE}
    else
       echo "Detected processes are..." >>${LOG_FILE}
       echo ${CMD} >>${LOG_FILE}
       echo "Archive control - `date` - terminating" >>${LOG_FILE}
       exit
    fi
}

############################################################################
#
# f_start_archive_monitor
#
# This function checks whether the archive monitor script is running and if
# it is not then it starts it
#
############################################################################

f_start_archive_monitor ()
{
    # If the script has been started by HANS, wait for the database 
    # subsystem to start before activating the archive monitor

    if [ "${HANS_START}" = "TRUE" ]
    then
        DB_RUNNING=""
        while [ "$DB_RUNNING" = "" ]
        do
            DB_RUNNING=`ps -eaf | grep db7305 | grep -v grep | awk '{print $2}'`
            sleep 1
        done
    fi

    MONITOR_RUNNING=`ps -eaf | grep archive_monitor.ksh | grep -v vi | grep -v grep | awk '{print $2}'`
    if [ "${MONITOR_RUNNING}" = "" ]
    then
       echo "Archive control - `date` - activating archive monitor" >>${LOG_FILE}
       ${BIN_DIR}/archive_monitor.ksh &
    else
       echo "Archive control - `date` - archive monitor already running - PID=x${MONITOR_RUNNING}x" >>${LOG_FILE}
    fi
}

############################################################################
#
# f_kill_archive_monitor
#
# This function kills the archive monitor script
#
############################################################################

f_kill_archive_monitor ()
{
    MONITOR_PID=`ps -eaf | grep archive_monitor.ksh | grep -v vi |  grep -v grep | awk '{print $2}'`
    kill -9 ${MONITOR_PID}
}

############################################################################
#
# f_check_node_state
#
# This function determines the state of the node
#
############################################################################

f_check_node_state ()
{
    NODE_STATE=`sysstate | grep "CURRENT NODE" | awk '{print $4}'`
    DB_STATE=`sysstate | egrep "Subsystem \(${THIS_NODE_NO}\)73 is disabled|Subsystem \(${THIS_NODE_NO}\)73 is starting up|Subsystem \(${THIS_NODE_NO}\)73 is not running"`

    # Check if the returned state is NULL - if so, the application is down

    if [ "${NODE_STATE}" = "" ]
    then
       NODE_STATE="Unavailable"
    else
       # Just double check the status of the database subsystem
       if [ "${DB_STATE}" != "" ]
       then
          # Set the status to indicate that the database subsystem is not running properly
          NODE_STATE="Available"
       fi
    fi
}

############################################################################
#
# f_check_standby_archive
#
# This function checks whether we really need to perform an archive by 
# checking various times and conditions. The return value is 1 if archive
# needs to be performed otherwise it is 0
#
############################################################################

f_check_standby_archive ()
{
    RETURN_VALUE=0  # Assume we do not want to perform an archive

    # Check whether there was an archive in progress when the 
    # Standby was last running.

    ARCH_STATUS=`sqlplus -s $APPN_DATABASE <<EOF
    set pagesize 0
    select status from archive_config where status like 'Start%'
    union all
    select status from live.archive_config where status like 'Start%'
    union all
    select status from arch.archive_config where status like 'Start%';
    exit
EOF`
    # Strip off any extraneous newlines
    ARCH_STATUS=`echo ${ARCH_STATUS} | tr -d '\012'`
    if [ "${ARCH_STATUS}" != "no rows selected" ]
    then
        # We were in the middle of an archive so we need to perform one

        echo "Archive control - `date` - Standby was archiving a user" >>${LOG_FILE}
        echo "Archive control - `date` - Therefore we need to archive" >>${LOG_FILE}
        RETURN_VALUE=1
    else
        # OK - so the status indicates that none of the users were being 
        # archived. But each user is archived in turn starting with ARCH
        # then moving onto LIVE and finally OPS$. Did we shutdown in between
        # users? Select the order in which the users were archived and if
        # it isn't ARCH LIVE OPS then we need to archive.  

        ARCH_ORDER=`sqlplus -s $APPN_DATABASE <<EOF
        set pagesize 0
        select username from 
        (    select username, userdate from
             (      select 'ARCH ' as username,
                           to_date(substr(status,instr(status,'at')+3),'YYYYMMDD HH24:MI:SS') as userdate 
                       from arch.archive_config
                    union all
                    select 'LIVE ' as username,
                            to_date(substr(status,instr(status,'at')+3),'YYYYMMDD HH24:MI:SS') as userdate 
                       from live.archive_config
                    union all
                    select 'OPS ' as username,
                           to_date(substr(status,instr(status,'at')+3),'YYYYMMDD HH24:MI:SS') as userdate 
                       from archive_config
              )
       )
       order by userdate,username;
       exit;
EOF`
       # Remove any newlines

       ARCH_ORDER=`echo ${ARCH_ORDER} | tr -d '\012'`
       echo "Archive control - `date` - Archive order on standby is ${ARCH_ORDER}" >>${LOG_FILE}

       # Now check whether the archive order is correct
 
       if [ "${ARCH_ORDER}" != "ARCH LIVE OPS" ]
       then 
          
           # Wrong order - we need to archive

           echo "Archive control - `date` - Standby was archiving between users" >>${LOG_FILE}
           echo "Archive control - `date` - Therefore we need to archive" >>${LOG_FILE}
           RETURN_VALUE=1
       
       else
           
           # The Standby wasn't shut down in the middle of archive so let's check 
           # the Master to find out where Master archive is up to. First - is there an 
           # archive currently running on the Master?      
           ARCH_STATUS=` ${REM_SHELL} ${OTHER_NODE} ". ~/.profile >/dev/null; sqlplus -s $APPN_DATABASE <<EOF
           set pagesize 0
           select status from archive_config where status like 'Start%'
           union all
           select status from live.archive_config where status like 'Start%'
           union all
           select status from arch.archive_config where status like 'Start%';
           exit
EOF"`
           ARCH_STATUS=`echo ${ARCH_STATUS} | tr -d '\012'`
           if [ "${ARCH_STATUS}" != "no rows selected" ]
           then

               # The Master is in the middle of an archive 
               # We therefore need to perform an archive on this node. 

               echo "Archive control - `date` - Master is currently archiving a user or has failed" >>${LOG_FILE}
               echo "Archive control - `date` - Therefore we need to archive" >>${LOG_FILE}
               RETURN_VALUE=1

           else
               # OK - so the status indicates that none of the users were being 
               # archived on the Master. But each user is archived in turn starting with ARCH
               # then moving onto LIVE and finally OPS$. So check whether archive is currently
               # between users on the Master? Select the order in which the users were archived and if
               # it isn't ARCH LIVE OPS then archive is taking place.

               ARCH_ORDER=` ${REM_SHELL} ${OTHER_NODE} ". ~/.profile >/dev/null; sqlplus -s $APPN_DATABASE <<EOF
               set pagesize 0
               select username from 
               (    select username, userdate from
                    (      select 'ARCH ' as username,
                                  to_date(substr(status,instr(status,'at')+3),'YYYYMMDD HH24:MI:SS') as userdate 
                              from arch.archive_config
                           union all
                           select 'LIVE ' as username,
                                   to_date(substr(status,instr(status,'at')+3),'YYYYMMDD HH24:MI:SS') as userdate 
                              from live.archive_config
                           union all
                           select 'OPS ' as username,
                                  to_date(substr(status,instr(status,'at')+3),'YYYYMMDD HH24:MI:SS') as userdate 
                              from archive_config
                     )
              )
              order by userdate;
              exit;
EOF"`
              # Remove any newlines

              ARCH_ORDER=`echo ${ARCH_ORDER} | tr -d '\012'`

              echo "Archive control - `date` - Archive order on master is ${ARCH_ORDER}" >>${LOG_FILE}
              # Now check whether the archive order is correct
 
              if [ "${ARCH_ORDER}" != "ARCH LIVE OPS"  ]
              then 
          
                  # Wrong order (archive is taking place on the Master)
                  # We need to archive on this node

                  echo "Archive control - `date` - Master is currently archiving between users" >>${LOG_FILE}
                  echo "Archive control - `date` - Therefore we need to archive" >>${LOG_FILE}
                  RETURN_VALUE=1
       
              else
                  
                  # Archive is not running on the Master so let's check whether 
                  # we need to run on the Standby by comparing the times that 
                  # archive ran on each node. Get the maximum archive complete time
                  # on each node and compare them (this will be the time that the 
                  # OPS$ archive completed).

                  SBY_ARCH_TIME=`sqlplus -s $APPN_DATABASE <<EOF
                  set pagesize 0
                  select substr(status,instr(status,'at')+3,8) from archive_config;
                  exit;
EOF`
                  MAST_ARCH_TIME=` ${REM_SHELL} ${OTHER_NODE} ". ~/.profile >/dev/null; sqlplus -s $APPN_DATABASE <<EOF
                  set pagesize 0
                  select substr(status,instr(status,'at')+3,8) from archive_config;
                  exit;
EOF"`
                  echo "Archive control - `date` - Master archive date is ${MAST_ARCH_TIME}" >>${LOG_FILE}
                  echo "Archive control - `date` - Standby archive date is ${SBY_ARCH_TIME}" >>${LOG_FILE}
                  if [[ "${SBY_ARCH_TIME}" < "${MAST_ARCH_TIME}" ]]
                  then 
                       # Archive on the Master has run while the Standby was down
 
                       echo "Archive control - `date` - Master archive has run since shutdown" >>${LOG_FILE}
                       echo "Archive control - `date` - Therefore we need to archive" >>${LOG_FILE}
                       RETURN_VALUE=1
                  fi 
              fi
          fi
       fi
    fi
  
    # Return
 
    return ${RETURN_VALUE}
}

############################################################################
#
# f_perform_archive
#
# This function performs the archive. It calls further functions to archive 
# the individual schemas.
#
############################################################################

f_perform_archive ()
{

    echo "Archive control - `date` - Perform archive" >>${LOG_FILE}

    START_DATE=`date +"%Y%m%d %H%M%S"`

    # Archive the ARCH schema first

    echo "Archive control - `date` - Archiving ARCH schema" >>${LOG_FILE}
    cd ${BIN_DIR}
    ./archive_arch

    sleep 1

    # Archive the LIVE schema
   
    echo "Archive control - `date` - Archiving LIVE schema" >>${LOG_FILE}
    ./archive_live

    sleep 1

    # Finally archive the OPS$ user

    echo "Archive control - `date` - Archiving OPS\$TAGTRAK schema" >>${LOG_FILE}
    sqlplus -s $APPN_DATABASE <<EOF 
    alter session set cursor_sharing=FORCE;
    exec pkg73_row_header.v_source:='ARCHIVE';
    exec pkg73_archive.p73_archive;
    exit;
EOF
    echo "Archive control - `date` - Archive Complete" >>${LOG_FILE}

    # Finally print the archive logs in the log file.

    echo "Archive control - `date` - Archive Logs are as follows:" >>${LOG_FILE}
    echo "===========================================================" >>${LOG_FILE}

    sqlplus -s $APPN_DATABASE <<EOF >>${LOG_FILE}
    set head off
    set line 200
    set pagesize 10000
    col text for a150
    select to_char (row_create_time+2/24,'YYYY/MM/DD HH24:MI:SS'),
           text||'-->'||parameters as text from system_logs where log_number like '7356%'
       and row_create_time+2/24 >= '${START_DATE}' order by 1;

    exit;

    echo "===========================================================" >>${LOG_FILE}
EOF

}

############################################################################
#
# f_master
#
# This function performs archive actions for node state MASTER
#
############################################################################

f_master ()
{
    # Check the state of the other node
 
    OTHER_NODE_STATE=`sysstate | grep "Node ${OTHER_NODE_NO} is" | awk '{print $4}'`
    echo "Archive control - `date` - Other node state is ${OTHER_NODE_STATE}" >>${LOG_FILE}

    if [ ${OTHER_NODE_STATE} = "Standby" ]
    then
        # The other node is Standby so activate the script on that node forcing
        # it to perform the archive rather than checking whether it should. 
         
        ${REM_SHELL} ${OTHER_NODE} ". ~/.profile; cd ${BIN_DIR}; nohup ./archive_control.ksh F" &
    else 
        if [ ${OTHER_NODE_STATE} = "Available" ]
        then
            # The other node is performing an FSU. Let's wait for that to finish
            # so that we don't lose any data. If the node state changes to 
            # anything else then the archive can be performed.
            
            echo "Archive control - `date` - waiting for Full Standby Update to finish on the other node" >>${LOG_FILE}
            while [ "${OTHER_NODE_STATE}" = "Available" ]
            do
                sleep 10
                OTHER_NODE_STATE=`sysstate | grep "Node ${OTHER_NODE_NO} is" | awk '{print $4}'`
                echo "Archive control - `date` - Other node state is ${OTHER_NODE_STATE}" >>${LOG_FILE}
            done
        fi

        # Check the new state of the other node. If it is Standby then kick off archive remotely too

        if [ ${OTHER_NODE_STATE} = "Standby" ]
        then
            # The other node is Standby so activate the script on that node forcing
            # it to perform the archive rather than checking whether it should. 
         
            ${REM_SHELL} ${OTHER_NODE} ". ~/.profile; cd ${BIN_DIR}; ./archive_control.ksh F" &
        fi
    fi

    # Now perform the archive on this node

    f_perform_archive
}

############################################################################
#
# f_standby
#
# This function performs archive actions for node state STANDBY
#
############################################################################

f_standby ()
{
    # We are running on the Standby and the state is STANDBY
    # Unless we are being forced to run archive, check whether we really 
    # should.

    if [ "${STANDBY_FORCE}" = "TRUE" ]
    then
       # We are being forced to archive so let's do it

       f_perform_archive
    
    else
       # If we have been started up by HANS, wait until Oracle has started first

       if [ "${HANS_START}" = "TRUE" ]
       then
           ERROR="ERROR"
           while [ "${ERROR}" = "ERROR" ]
           do
                ORASTATE=`sqlplus -s $APPN_DATABASE <<EOF
                set pagesize 0
                select sysdate from dual;
                exit;
EOF`
                ERROR=`echo ${ORASTATE} | cut -c 1-5`
           done
       fi

       # We are not being forced, so let's check whether we really need to archive

       f_check_standby_archive
       if [ $? = 1 ]
       then 
           # Conditions are correct to perform the archive
           # Wait until Full Standby Update is running and then pause it

           # Perform the archive 

           f_perform_archive

           # Check the state of archive on the Master node. If it is still going on then 
           # wait for it to finish before unleashing FSU. This will prevent data that we 
           # have already archived being copied back across again by FSU.

           echo "Archive control - `date` - waiting for Archive to finish on the Master Node" >>${LOG_FILE}

           # Set a flag to indicate whether we need to wait for Master Archive to finish before
           # we can unleash FSU on an unsuspecting Standby

           COMPLETE_ARCHIVE="N"
           while [ "${COMPLETE_ARCHIVE}" = "N" ]
           do
               # Check whether a user is currently being archived on the Master node

               MAST_ARCH_STATUS=` ${REM_SHELL} ${OTHER_NODE} ". ~/.profile >/dev/null; sqlplus -s $APPN_DATABASE <<EOF
               set pagesize 0
               select status from archive_config where status like 'Start%'
               union all
               select status from live.archive_config where status like 'Start%'
               union all
               select status from arch.archive_config where status like 'Start%';
               exit
EOF"`
               MAST_ARCH_STATUS=`echo ${MAST_ARCH_STATUS} | tr -d '\012'`
               if [ "${MAST_ARCH_STATUS}" != "no rows selected" ]
               then
                   # Archive is still going on on the Master node. Sleep for 10 seconds.
                   echo "Archive control - `date` - Master Archive Status is ${MAST_ARCH_STATUS} - waiting for Master archive completion" >>${LOG_FILE} 
                   sleep 10
               else
                   # OK - so the status indicates that none of the users were being 
                   # archived. But each user is archived in turn starting with ARCH
                   # then moving onto LIVE and finally OPS$. Is the Master currently in between
                   # users? Select the order in which the users were archived and if
                   # it isn't ARCH LIVE OPS then we need to archive.  

                   MAST_ARCH_ORDER=` ${REM_SHELL} ${OTHER_NODE} ". ~/.profile >/dev/null; sqlplus -s $APPN_DATABASE <<EOF
                   set pagesize 0
                   select username from 
                   (    select username, userdate from
                        (      select 'ARCH ' as username,
                                      to_date(substr(status,instr(status,'at')+3),'YYYYMMDD HH24:MI:SS') as userdate 
                                  from arch.archive_config
                               union all
                               select 'LIVE ' as username,
                                       to_date(substr(status,instr(status,'at')+3),'YYYYMMDD HH24:MI:SS') as userdate 
                                  from live.archive_config
                               union all
                               select 'OPS ' as username,
                                      to_date(substr(status,instr(status,'at')+3),'YYYYMMDD HH24:MI:SS') as userdate 
                                  from archive_config
                         )
                  )
                  order by userdate,username;
                  exit;
EOF`
                  # Remove any newlines

                  MAST_ARCH_ORDER=`echo ${MAST_ARCH_ORDER} | tr -d '\012'`

                  # Now check whether the archive order is correct
 
                  if [ "${MAST_ARCH_ORDER}" != "ARCH LIVE OPS" ]
                  then 
                     # Archive is still going on on the Master node. Sleep for 10 seconds.
                     echo "Archive control - `date` - Master Archive Order is ${MAST_ARCH_ORDER} - waiting for Master archive completion" >>${LOG_FILE} 
                     sleep 10
                  else 
                     # We can unleash FSU
                     COMPLETE_ARCHIVE="Y"
                  fi
             fi
           done
       else
           # Not performing the archive
           echo "Archive control - `date` - not performing the Standby archive" >>${LOG_FILE}
       fi
       rm $APPN_WORKDIR/sby/stop_fsu
    fi
}

###########################################################################
#
#   M  A  I  N     C  O  D  E
#
###########################################################################

if [ "$1" = "-help" ]
then
    # Display help information
    f_help
    exit;
fi

# Determine which remote shell we are using. 
# REM_SHELL determines this but # if not set, default to rsh

if [ "${REM_SHELL}" = "" ]
then
    REM_SHELL=rsh
fi

# Get date to filter 'clone' shells
DT=`date "+%H:%M:%S"`

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

LOG_FILE=${TRAK_HOME}/log/archive.log

echo "Archive control - `date` - starting with parameter $1"  >>${LOG_FILE}

# Preset the variables we need

f_initialise

# Check whether there is another copy of the script running

f_check_script_running ${DT}

# Determine what we are going to do according to the supplied parameter 

if [ "$1" = "F" ]
then 
    # We are forcing the archive if this is the Standby

    STANDBY_FORCE="TRUE"
else 
    STANDBY_FORCE="FALSE"
fi

if [ "$1" = "P" ]
then 
    # Activated by HANS

    echo "Archive control - `date` - we have been activated by HANS" >>${LOG_FILE}
    HANS_START="TRUE"

    # Check the state of the other node 

    OTHER_NODE_STATE=`sysstate | grep "Node ${OTHER_NODE_NO} is" | awk '{print $4}'`
    echo "Archive control - `date` - Other node state is ${OTHER_NODE_STATE}" >>${LOG_FILE}

    if [ ${OTHER_NODE_STATE} = "Unavailable" ]
    then
        # We are the only node. Assume that we are going to become Master and terminate.
        # System Events will reactivate if necessary.

        echo "Archive control - `date` - Activated by HANS on what will become Master - terminating" >>/${LOG_FILE}
        exit
    else
        # Assume this node will become Standby. Pause FSU until after we have completed archive.
        # If we become Master then the file will be deleted anyway.

        touch $APPN_WORKDIR/sby/stop_fsu
    fi
else 
    HANS_START="FALSE"
    echo "Archive control - `date` - we have been activated by System Events" >>${LOG_FILE}
fi

# Start up the archive monitor script if it is not already running

f_start_archive_monitor

# Determine the node state

f_check_node_state

echo "Archive control - `date` - This node is ${NODE_STATE}" >>${LOG_FILE}

# The action to take is determined by the state of the node

case ${NODE_STATE} in 
    "Master")     
                    # This is the Master node

                    if [ "${HANS_START}" = "TRUE" ]
                    then
                        # Activated by HANS on the Master so terminate
                        # and kill the monitor as well

                        f_kill_archive_monitor
                        echo "Archive control - `date` - Activated by HANS on Master - terminating" >>/${LOG_FILE}
                        rm $APPN_WORKDIR/sby/stop_fsu
                        exit
                    else
                        # Run as normal

                        f_master
                    fi
                    ;;
    "Standby") 
                    # This is the Standby node

                    f_standby
                    ;;

    "Available")    # FSU is taking place or is about to take place on this node

                    if [ "${HANS_START}" = "TRUE" ]
                    then
                        # We have been activated by HANS therefore we need
                        # to jump in before Full Standby Update
                        f_standby
                    else
                        # FSU is running -  and we've been activated illegally.
                        # We don't want to run now so let's terminate

                        echo "Archive control - `date` - Activated without parameter when FSU is running - terminating" >>/${LOG_FILE}
                        exit;
                    fi
                    ;;

    "Unavailable")  # The application is down - simply terminate

                    exit
                    ;;
esac

# Finally terminate the archive monitor script

f_kill_archive_monitor

echo "Archive control - `date` - terminating" >>${LOG_FILE}
