#!/bin/sh

if [ $# -gt 0 ]; then
  sleep `expr $RANDOM \% $1`
fi

# if set to false sam-sync will not invoke database
# components (MRS, POEM, ATP). This is used on site 
# and security instances
MRS_ENABLED=true

if [ -f /etc/sysconfig/sam-sync ] ; then
  . /etc/sysconfig/sam-sync
fi

ATP_ACTIVE=1
POEM_ACTIVE=1

if [ $MRS_ENABLED == "true" ] ; then
  # Check if atp-sync is active
  /sbin/service atp-sync status > /dev/null 2>&1
  if [ $? -ne 0 ]; then
    echo "INFO: atp-sync is not active, will not restart it"
    ATP_ACTIVE=0
  fi

  # Check if poem-sync is active
  /sbin/service poem-sync status > /dev/null 2>&1
  if [ $? -ne 0 ]; then
    POEM_ACTIVE=0
    echo "INFO: poem-sync is not active, will not restart it"
  fi

  if [ $ATP_ACTIVE -eq 1 ]; then
    /sbin/service atp-sync stop > /dev/null 2>&1
    if [ $? -ne 0 ]; then
      echo "ERROR: stopping service atp-sync failed, please check atp logs."
      echo "ERROR: ncg and mrs-bootstrapping will not be run."
      exit 1
    fi
  fi

  if [ $POEM_ACTIVE -eq 1 ]; then
    /sbin/service poem-sync stop > /dev/null 2>&1
    if [ $? -ne 0 ]; then
      echo "ERROR: stopping service poem-sync failed, please check poem logs."
      echo "ERROR: ncg and mrs-bootstrapping will not be run."

      if [ $ATP_ACTIVE -eq 1 ]; then
        echo "INFO: trying to switch on atp-sync before exit."
        /sbin/service atp-sync start
      fi
    
      exit 1
    fi
  fi
fi

# From this point script does not exit in order to allow
# atp-sync and poem-sync to recover
# If any invoked script fails script will return 1
RETVAL=0

# First try to run NCG
( /usr/sbin/ncg.reload.sh 2>&1 ) | gawk '{print strftime(), ":", $0}'  >> /var/log/ncg.log
if [ $PIPESTATUS -ne 0 ]; then
  echo "ERROR: ncg failed, please check /var/log/ncg.log."
  echo "ERROR: mrs-bootstrapper will not be run."
  RETVAL=1
fi

if [ $MRS_ENABLED == "true" ] ; then
  # If the NCG was successful try MRS
  if [ $RETVAL -eq 0 ]; then
    python /usr/sbin/mrs-bootstrapper --node=sam-nagios --timeout=$MRS_BOOTSTRAPPER_TIMEOUT >> /var/log/mrs-bootstrapper.log 2>&1
    if [ $? -ne 0 ]; then
      echo "ERROR: mrs-bootstrapper failed, check /var/log/mrs-bootstrapper.log."
      RETVAL=1
    fi
  fi

  if [ $ATP_ACTIVE -eq 1 ]; then
    /sbin/service atp-sync start > /dev/null 2>&1
    if [ $? -ne 0 ]; then
      echo "ERROR: starting service atp-sync failed, please check atp logs."
      RETVAL=1
    fi
  fi

  if [ $POEM_ACTIVE -eq 1 ]; then
    /sbin/service poem-sync start > /dev/null 2>&1
    if [ $? -ne 0 ]; then
      echo "ERROR: starting service poem-sync failed, please check poem logs."
      RETVAL=1
    fi  
  fi
fi

if [ $RETVAL -eq 0 ]; then
  echo "INFO: sam-sync successfully executed."
fi

exit $RETVAL
