#!/bin/bash
#
# chkconfig: - 09 91
# description: Initialize the Shoreline Firewall at boot time.

# Source function library
if [ -f /etc/init.d/functions ]; then
  . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ]; then
  . /etc/rc.d/init.d/functions
else
  exit 0
fi

# Detect our basename
TMP_NAME=$0
TMP_PWD=$PWD
while [ -L $TMP_NAME ]; do
  if [ ${TMP_NAME/\/} != $TMP_NAME ]; then
    cd ${TMP_NAME%/*}
  fi
  TMP_NAME=$(readlink ${TMP_NAME##*/})
done
cd $TMP_PWD
declare -r BASENAME=${TMP_NAME##*/}
unset TMP_NAME
unset TMP_PWD

# Source service configuration.
if [ -f /etc/sysconfig/${BASENAME} ]; then
  . /etc/sysconfig/${BASENAME}
else
  echo "${BASENAME}: configfile /etc/sysconfig/${BASENAME} does NOT exist!"
  exit 6
fi

# Initialize the firewall
start() {
  local product
  local vardir

  if [ -z "$PRODUCTS" ]; then
    echo -n $"No firewalls configured for shorewall-init"
    failure
    echo
    return 6
  fi

  echo -n $"Initializing Shorewall-based firewalls: "
  for product in $PRODUCTS; do
    vardir=/var/lib/${product}
    [ -f /etc/${product}/vardir ] && . /etc/${product}/vardir 
    if [ -x ${vardir}/firewall ]; then
      ${vardir}/firewall stop > /dev/null 2>&1
      RETVAL=$?
      [ $RETVAL -ne 0 ] && break
    fi
  done

  if [ $RETVAL -eq 0 ]; then
    touch /var/lock/subsys/${BASENAME}
    success
  else
    failure
  fi
  echo
  return $RETVAL
}

# Clear the firewall
stop() {
  local product
  local vardir

  echo -n $"Clearing Shorewall-based firewalls: "
  for product in $PRODUCTS; do
    vardir=/var/lib/${product}
    [ -f /etc/${product}/vardir ] && . /etc/${product}/vardir 
    if [ -x ${vardir}/firewall ]; then
      ${vardir}/firewall clear > /dev/null 2>&1
      RETVAL=$?
      [ $RETVAL -ne 0 ] && break
    fi
  done

  if [ $RETVAL -eq 0 ]; then
    rm -f /var/lock/subsys/${BASENAME}
    success
  else
    failure
  fi
  echo
  return $RETVAL
}

svcstatus() {
  status $BASENAME
  RETVAL=$?
  return $RETVAL
}

RETVAL=0

# See how we were called.
case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
    svcstatus
    ;;
  *)
    echo $"Usage: $BASENAME {start|stop|status}"
    RETVAL=1
esac

exit $RETVAL
