#!/bin/sh
# Written by Steven Shiau <steven@nchc.org.tw> to use in DRBL for RedHat
# License: GPL
#
# set the iptables NAT
# clean the old tables

# Load DRBL setting and functions
if [ ! -f "/opt/drbl/sbin/drbl-conf-functions" ]; then
  echo "Unable to find /opt/drbl/sbin/drbl-conf-functions! Program terminated!" 
  exit 1
fi
. /opt/drbl/sbin/drbl-conf-functions

#
check_if_root

# main
USAGE="Usage: $0 {on|off}"
switch=$1

#
if [ $# -ne 1 ]; then
  echo "$USAGE"
  echo "Example: use the following to set the YP securenets"
  echo "$0 on"
  exit 1
fi
#
case "$switch" in
   "on")
      echo "Now set the YP securenets..."
      if [ -f /var/yp/securenets ]; then 
        echo "Backup the original /var/yp/securenets as /var/yp/securenets.drblsave"
        mv -f /var/yp/securenets /var/yp/securenets.drblsave
      fi

time_now="$(date "+%T %Y/%m/%d")"

      cat <<EOF > /var/yp/securenets
# Generated by DRBL at $time_now
EOF
      cat <<EOF >> /var/yp/securenets
255.0.0.0	127.0.0.0
EOF

# we assume the server will use eth0 or eth0:1 as the interface to WAN
# we just turn on eth0 and eth0:1 for the server to access the YP, no matter
# it's private or public.
      for ethx in eth0 eth0:1; do
        wan_ip="$($DRBL_SCRIPT_PATH/bin/get_ip $ethx)"
        if [ -n "$wan_ip" ]; then
      cat <<EOF >> /var/yp/securenets
255.255.255.255 $wan_ip
EOF
        fi
      done

# for DRBL clients
      for ihost in $drblroot/*; do
        ip="$(basename $ihost)"
      cat <<EOF >> /var/yp/securenets
255.255.255.255 $ip
EOF
      done
      echo "done!"
      ;;
    off)
      echo "Now disable the YP access for DRBL clients..."
      if [ -f /var/yp/securenets ]; then 
        echo "Remove the /var/yp/securenets..."
        mv -f /var/yp/securenets /var/yp/securenets.drblsave
      fi
      echo "done!"
      ;;
    *)
      echo "$USAGE"
esac
