#!/bin/sh

set_defaultrouter() {
  route add default $DEFAULTROUTER >/dev/null 2>&1
}

set_hostname() {
  hostname $HOSTNAME
}

set_iface() {
  #Stopping the dhclient if present
  DHCLIENT_PID=`ps -x | grep "dhclient -nw $IFACE_NAME" | \
                awk '{print $1}'`
  [ "$DHCLIENT_PID" != "" ] && kill $DHCLIENT_PID >/dev/null 2>&1
  ifconfig $IFACE_NAME $IFACE_ARGS
}

# Find the already mounted partitions in /mnt
CONFIGFILE_NAME="freesbie_settings.conf"
GOOD_PARTITIONS=`mount | grep mnt | cut -d\  -f 3`
for i in $GOOD_PARTITIONS 
do
  IS_PRESENT=`ls $i/${CONFIGFILE_NAME} 2>/dev/null`
  if [ "${IS_PRESENT}" != "" ]; then
    echo "Reading saved settings from $i/${CONFIGFILE_NAME}"
    . $i/${CONFIGFILE_NAME}

    #Set the hostname
    [ "$HOSTNAME" != "" ] && set_hostname

    #Network interfaces setup
    for j in 0 1 2 3 4 5 6 7 
    do
      eval IFACE=\$NETWORK_IFACE$j
      if [ "$IFACE" != "" ]; then
        IFACE_NAME=`echo $IFACE | cut -d, -f 1`
        IFACE_ARGS=`echo $IFACE | cut -d, -f 2`
        set_iface
      fi
    done

    #Default router setup
    [ "$DEFAULTROUTER" != "" ] && set_defaultrouter

    #Other settings
  fi
done
