#!/bin/bash

###########################################################################
#
# MODULE:       LFS
# AUTHOR:	CacheGuard Technologies
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###########################################################################

. /lib/lsb/init-functions
. ${IFCONFIG}

case "${TYPE}" in
   ("fwmark")
      need_fwmark=1
   ;;

   (*)
      log_failure_msg "Unknown rule type (${TYPE}) in ${IFCONFIG}, cannot continue."
      exit 1
   ;;
esac

if [ -n "${PRIORITY}" ]; then
   args="${args} priority ${PRIORITY}"
fi

if [ -n "${need_fwmark}" ]; then
   if [ -z "${FWMARK}" ]; then
      log_failure_msg "FWMARK variable missing from ${IFCONFIG}, cannot continue."
      exit 1
   fi

   args="${args} fwmark ${FWMARK}"
   desc="${desc}${FWMARK} Firewall Mark Routing"
fi

if [ -n "${TABLE}" ]; then
   args="${args} table ${TABLE}"
fi

if [ -n "${IIF}" ]; then
   args="${args} iif ${IIF}"
fi

if [ -n "${OIF}" ]; then
   args="${args} oif ${OIF}"
fi

case "${1}" in
   up)
      log_info_msg "Adding '${desc}' rule..."
      ip rule add ${args}
      evaluate_retval
   ;;
   
   down)
      log_info_msg "Removing '${desc}' rule..."
      ip rule del ${args}
      first_status=${?}
      status=${first_status}
      while [ ${status} -eq 0 ]
      do
	  ip rule del ${args} 2> /dev/null
	  status=${?}
      done
      [ ${first_status} -eq 0 ]
      evaluate_retval
   ;;
   
   *)
      echo "Usage: ${0} [rule] {up|down}"
      exit 1
   ;;
esac

# End /lib/services/ip-rule
