#!/bin/sh
# Author: Blake, Kuo-Lien Huang
# Description:

default_kernel_ver="2.4.25"

case $1 in
  "start")
    kernel_ver=`uname -r`
    if [ ! -d /tftpboot/$kernel_ver ]; then 
      kernel_ver="$default_kernel_ver"
    fi

    ## etherboot
    rm -f /tftpboot/*.nbi
    for nbi in `ls /tftpboot/$kernel_ver`; do
      ln -fs $kernel_ver/$nbi /tftpboot/$nbi
    done
    ln -fs $kernel_ver/dhcpd.conf.etherboot-pcimap.include /etc/dhcp3/dhcpd.conf.etherboot-pcimap.include
    ln -fs $kernel_ver/dhcpd.conf.etherboot.include /etc/dhcp3/dhcpd.conf.etherboot.include
    touch /etc/dhcp3/dhcpd.conf.client-switch.include
    chmod 600 /etc/dhcp3/dhcpd.conf.client-switch.include

    ## pxe    
    ln -fs vmlinuz-$kernel_ver /tftpboot/vmlinuz
    ln -fs initrd-pxe_pciscan-$kernel_ver.img /tftpboot/initrd-pxe_pciscan.img

    ## routing table
    if [ "$2" != "no_routing_table" ]; then

      same_subnet=0

      for netdevA in `cat /proc/net/dev | awk -F: '/eth.:|tr.:/{print $1}'`; do

        ipA="$(/sbin/ifconfig $netdevA | grep "inet addr" | cut -d: -f2 | cut -d' ' -f1)"
        netmaskA="$(/sbin/ifconfig $netdevA | grep "inet addr" | cut -d: -f4 | cut -d' ' -f1)"
        if [ "$ipA" = "" -o "$netmaskA" = "" ]; then continue; fi
  
        networkA="$(/usr/bin/netmask $ipA/$netmaskA)"

        for netdevB in `cat /proc/net/dev | awk -F: '/eth.:|tr.:/{print $1}'`; do

          if [ "$netdevB" = "$netdevA" ]; then continue; fi

          ipB="$(/sbin/ifconfig $netdevB | grep "inet addr" | cut -d: -f2 | cut -d' ' -f1)"
          netmaskB="$(/sbin/ifconfig $netdevB | grep "inet addr" | cut -d: -f4 | cut -d' ' -f1)"
          if [ "$ipB" = "" -o "$netmaskB" = "" ]; then continue; fi
    
          networkB="$(/usr/bin/netmask $ipB/$netmaskB)"

          #echo "A=$networkA B=$networkB"
          if [ "$networkA" = "$networkB" ]; then same_subnet=1; break; fi

        done

        if [ $same_subnet -eq 1 ]; then break; fi

      done

      ## same subnet
      if [ $same_subnet -eq 1 -a -f /opt/drbl/sbin/drblpush ]; then
        export GPL=0; /opt/drbl/sbin/drblpush --routing-table
      fi

    fi

    ;;
  "stop")
    ;;
esac
