#!/bin/sh
# Author: Blake, Kuo-Lien Huang
# License: GPL
# Descrition:
#   help user to write mapping file for iptrans.pl
#   1. generate template mapping file
#   2. validate the mapping file before execute 

# iptrans.pl & validate.pl
tail +${LINENO} $0 > iptrans.pl
chmod 755 iptrans.pl
cat <<-EOF > validate.pl
#!/usr/bin/perl
\$lineno=0;
open(MAP,\$ARGV[0]);
while(<MAP>) {
  chomp;
  \$lineno++;
  if(/^#/ || /^$/) { next; }
  elsif(/([^\/]*)\/([^\t]*)\t([^\/]*)\/([^\t]*)/) { next; }
  elsif(/([^\t]*)\t([^\t]*)/) {
    if(\$1 =~ /^$/ || \$2 =~ /^$/ || \$1 =~ /([^\/]*)\/([^\t]*)/) { print "\$lineno\n"; last; }
    next;
  }
  else { 
    print "\$lineno\n";
    last;
  }
}
close(MAP);
EOF
chmod 755 validate.pl

##
TMP=`mktemp /tmp/mapping.XXXXXX`
#MAPPING="/tmp/mapping.$$"
MAPPING=`mktemp /tmp/mapping.XXXXXX`

while read line 
do

  # network/netmask
  if [ "$(echo "$line" | grep -e "subnet.*netmask.*")" != "" ]; then
    network=`echo $line | awk '{ print $2; }'`
    netmask=`echo $line | awk '{ print $4; }'`
    echo >> $MAPPING
    #echo -e "$network/$netmask\t" >> $MAPPING
    echo "$network/$netmask" >> $TMP
  fi

  # ip
  if [ "$(echo "$line" | grep -e "fixed-address")" != "" ]; then
    ip=`echo $line | cut -d\; -f1 | awk '{ print $2; }'`
    #echo -e "$ip\t" >> $MAPPING
    echo "$ip" >> $TMP
  fi
  if [ "$(echo "$line" | grep -e "option routers")" != "" ]; then
    ip=`echo $line | cut -d\; -f1 | awk '{ print $3; }'`
    #echo -e "$ip\t" >> $MAPPING
    echo "$ip" >> $TMP
  fi

done < /etc/dhcp3/dhcpd.conf

validate=0
while [ $validate -ne 1 ]
do
  # edit the mapping file
  #vi $MAPPING
  nano $TMP

  # validate the mapping file
  rm -f $MAPPING
  while read A B 
  do
    if [ "$A" = "" -a "$B" = "" ] ; then
      echo >> $MAPPING
    else
      echo -e "$A\t$B" >> $MAPPING
    fi
  done < $TMP
 
  lineno=`./validate.pl $MAPPING`
  if [ "$lineno" = "" ]; then 
    validate=1
  else
    echo -n "Line $lineno is not correct! Press any key to edit .."
    read pause
  fi
done

# execute
./iptrans.pl $MAPPING

rm -f $MAPPING $TMP
rm -f iptrans.pl validate.pl

# restart services
SERVICES="/etc/rcS.d/S40networking /etc/rcS.d/S41portmap /etc/rc2.d/S19nis /etc/rc2.d/S20inetd /etc/rc2.d/S20ssh /etc/rc2.d/S20xfs /etc/rc2.d/S20dhcp3-server /etc/rc2.d/S23ntp /etc/rc2.d/S25nfs-user-server /etc/rc2.d/S99drblmgrd"
for SERVICE in $SERVICES
do
  if [ -e $SERVICE ]; then $SERVICE restart; fi
done
if [ -e /etc/rc2.d/S99drblmgrd ]; then /etc/rc2.d/S99drblmgrd start; fi
exit 0
