#!/bin/bash

# This script gets called by albator on iked crash
# The number of restarts is monitored here and limited
# to 3 subsequent abnormal failures.
# The daemon will get a chance to be restarted on the
# next access up/down event.
# The main reason for iked crash is a mismatch between
# the blackIP in the conf file and the actual network
# config on the system.

. /opt/itrnet/bin/scripts/access/NetworkUtils

BINDIR="/usr/iked"
ETCDIR="/etc/iked"
MAXRESTARTS=3

logit()
{
  logger -p authpriv.warning -t IKEDFAILURE "$@"
}

# blackMismatch
# Checks whether the blackIP declared in the ike config file
# really exists on the system
blackMismatch() {
  bIP=`grep blackip $ETCDIR/iked.conf | sed 's/.*=\"//'`
  bIf=`grep blackif $ETCDIR/iked.conf | sed 's/.*=\"//'`
  rIP=`getIPaddr $bIf`
  # if bIf is dummy, we already switched back to default conf
  if [ "$bIP" = "$rIP" ];then
    return 0
  elif [ "$bIf" = "dummy" ];then
    return 2
  else
    logit "mismatch: blackIP=$bIP, realIP=$rIP"
    return 1
  fi
}

# cleanIke
# removes pid files (or troubles expected e.g. on "ike clr" cmd)
# kill agent processes that may still be lying around
cleanIke() {
  killall radiusagent > /dev/null 2>&1
  killall dhcpagent > /dev/null 2>&1
  rm -f /var/run/iked* > /dev/null 2>&1
}

#### MAIN ####

restartCount=0
nbParams=$#

if [ $nbParams -eq 1 ];then
  if [ -n "`echo $1 | grep [^0-9]`" ];then
    logit "called with bad argument: $1"
    exit 1
  fi
  restartCount=$1
fi

cleanIke

blackMismatch
bMis=$?

# If blackIP incorrect, get back to default config file
# Even if IP is correct, do the same as a last attempt after 2 restarts
if [ $bMis -eq 1 ] || ( [ $bMis -eq 0 ] && [ $restartCount -ge 2 ] );then
  logit "Going back to tempo file after $restartCount restarts"
  cp -f /etc/iked/iked.conf.tempo /etc/iked/iked.conf
fi

if [ $restartCount -lt $MAXRESTARTS ];then
  newCount=`expr $restartCount + 1`
  logit "Relaunching daemon, attempt #$newCount"
  /opt/itrnet/bin/iagw --cmd start "iked" "D" "$BINDIR/iked" "-c "$ETCDIR/iked.conf" -l 0 >/dev/null 2>&1" -1 "$ETCDIR/`basename $0`" "$newCount" "T"
else
  logit "Giving up after $restartCount restarts"
fi
