#! /bin/sh

INSTALL_DIR=$( cd "$( dirname "$0" )" && pwd )/..

# The exit codes returned by this script.
SUCCESS_NO_PENDING=0
SUCCESS_PENDING=30
SUSPEND_ALL_FAILURE=50
SUSPEND_NOW_ALL_FAILURE=55
STOP_FAILURE=60
SUCCESS_CODE=

wait_first()
{
echo 'Waiting 30 seconds to allow pending requests to end...'
sleep 30

echo 'Interrupting all remaining pending requests...'
$INSTALL_DIR/bin/iadmin.sh suspend-now all

case $? in
  $SUCCESS_NO_PENDING)
    stop_service
    ;;
  $SUCCESS_PENDING)
    stop_service
    ;;
  *)
    suspend_now_all_failure
    ;;
esac
}

stop_service()
{
echo 'Stopping Integration Agent daemon...'
$INSTALL_DIR/bin/stop_daemon.sh

if [ $? -ne 0 ] ; then 
  stop_failure
fi

echo 'Successfully shut down Integration Agent daemon...'
exit $SUCCESS_CODE
}

suspend_all_failure()
{
echo 'Failed to issue "suspend all" command via IA Admin CLI.'
echo 'Consult the script output and IA Admin CLI log files for details.'
exit $SUSPEND_ALL_FAILURE
}

suspend_now_all_failure()
{
echo 'Failed to issue "suspend-now all" command via IA Admin CLI.'
echo 'Consult the service output and IA Admin CLI log files for details.'
exit $SUSPEND_NOW_ALL_FAILURE
}

stop_failure()
{
echo 'Unable to stop Integration Agent daemon due to error code $?'
echo 'Consult the script output, system event log, or Integration Agent logs for details.'
exit $STOP_FAILURE
}

# Suspend all Integration Services.
echo 'Suspending all Integration Services...'
$INSTALL_DIR/bin/iadmin.sh suspend all

case $? in 
  $SUCCESS_NO_PENDING)
    SUCCESS_CODE=$SUCCESS_NO_PENDING
    stop_service
    ;; 
  $SUCCESS_PENDING) 
    SUCCESS_CODE=$SUCCESS_PENDING
    wait_first
    ;; 
  *)
    suspend_all_failure
    ;;
esac

