#!/bin/bash
# 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
#
if [ -e /etc/debian_version ]; then
  # Debian
  securenets_file=/etc/ypserv.securenets
else
  # RH-like or SUSE
  securenets_file=/var/yp/securenets
fi
case "$switch" in
   "on")
      echo "Now set the YP securenets..."
      echo "Backup the original $securenets_file as $securenets_file.drblsave"
      [ -f "$securenets_file" ] && mv -f $securenets_file ${securenets_file}.drblsave
      time_now="$(date "+%T %Y/%m/%d")"
      cat <<EOF > $securenets_file
# Generated by DRBL at $time_now
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 >> $securenets_file
255.255.255.255 $wan_ip
EOF
        fi
      done

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