#!/bin/sh
############################################################
# Copyright 2002-2005 The Lunar Linux Team                 #
############################################################
# lnet is a menu driven configurator for the networking    #
# init script                                              #
############################################################
# Hacked up by Rick Altherr for his purposes (muhuhahaha)  #
#                                                          #
# Just kidding.  This is an adaption of the network config #
# contained within the Lunar install script.               #
#                                                          #
# this code is GPLv2                                       #
############################################################

CONFIG_DIR="/etc/config.d/network"

catch_sig() {
  clear
  if [ -f /tmp/lnet.resolv.conf ]; then
    mv /tmp/lnet.resolv.conf /etc/resolv.conf
  fi
  if [ -f /tmp/lnet.$DEVICE ]; then
    mv /tmp/lnet.$DEVICE $OUT_TO
  fi

  # /tmp could have wireless WEPKEYS, so if we worked on more than one
  # device, we're only trying to save one, we're going to kill any others
  rm -f /tmp/lnet.*
  echo "Tried to restore device config file and resolv.conf from /tmp"
  echo "Ouch * that hurt you may want to double check /tmp"
  exit 1
}

msgbox() {
  if [ -z "$3" ]; then H=10; else H=$3; fi
  $DIALOG --title "$1" --msgbox "$2" $H 50
}

inputbox() {
  $DIALOG --nocancel --inputbox "$1" 0 0 "$2"
}

confirm() {
  $DIALOG $2 --yesno "$1" 8 50
}

goodbye() {
  clear
  exit  0
}

get_dev_list() {
  /bin/ls -1 $CONFIG_DIR | sort
}

get_dev_status() {
  L=`/sbin/ifconfig | grep "^$1[[:space:]]" | wc -l | tr -d ' \t\n'`
  if [[ "$L" -eq "0" ]]; then
    echo "[DOWN]"
  else
    echo "[_UP_]"
  fi
}

main ()
{
  unset PROMPT
  while true; do
    COUNTER=0
    unset LIST
    for DEVICE in `get_dev_list`; do
        if [ -L $CONFIG_DIR/$DEVICE ]; then
	    continue
	fi
        STATUS=`get_dev_status $DEVICE`
	INTERFACES[$COUNTER]=$DEVICE
	if [ -z "$LIST" ]; then
	  LIST="$COUNTER\nEdit device $DEVICE     $STATUS\n"
	else
	  LIST="$LIST$COUNTER\nEdit device $DEVICE     $STATUS\n"
	fi
	(( COUNTER++ ))
    done
    COMMAND=`$DIALOG  --title "Network configuration" \
                      --ok-label "Select"            \
		      --cancel-label "Exit"          \
                      --menu                         \
		      ""                             \
                      0 0 0                          \
		      $(echo -en $LIST)              \
                      "A"  "Add a network device"    \
                      "D"  "Setup DNS configuration" \
		      "N"  "Setup host and domain name" \
		      "G"  "Setup global Gateway" \
		      "M"  "Manage network devices"`

    if [ $? != 0 ] ; then
      return
    fi

    case $COMMAND in
      [0-9]*) ethernet_menu ${INTERFACES[$COMMAND]} ;;
      A)      ethernet_config ;;
      D)      dns_config ;;
      N)      hostname_config ;;
      G)      gateway_config ;;
      M)      ethernet_manage_menu ;;
    esac
  done
}

function dns_config() {
  RESOLV="/etc/resolv.conf"

  cp -p $RESOLV /tmp/lnet.resolv.conf

  DOMAIN_PROMPT="Enter Primary local Domain name"
  DNS1_PROMPT="Enter Primary DNS Server IP Address"
  DNS2_PROMPT="Enter Secondary DNS Server IP Address"
  SEARCH_PROMPT="Enter (optionally) domain name search order"

  DNS1="`grep nameserver $RESOLV | head -n 1 | cut -d \" \" -f2`"
  DNS2="`grep nameserver $RESOLV | head -n 2 | tail -n 1 | cut -d \" \" -f2`"
  DOMAIN="`grep domain $RESOLV | head -n 1 | cut -d \" \" -f2`"
  SEARCH="`grep search $RESOLV | head -n 1 | cut -d \" \" -f2-`"

  DNS1=${DNS1:-${IP%.*}.254}
  DOMAIN=${DOMAIN:-subd.com}

  DOMAIN=`inputbox "$DOMAIN_PROMPT" $DOMAIN`
  DNS1=`inputbox "$DNS1_PROMPT" $DNS1`

  if [ -z $DNS2 ]; then
    if [ -z $DNS1 ]; then
      DNS2=""
    else
      N_DNS=$((${DNS1##*.}+1))
      DNS2="${DNS1%.*}.$N_DNS"
    fi
  fi
  DNS2=`inputbox "$DNS2_PROMPT" "$DNS2"`
  SEARCH=`inputbox "$SEARCH_PROMPT" $SEARCH`

  (
    [ -z "$DOMAIN" ] || echo "domain $DOMAIN"
    [ -z "$DNS1" ]   || echo "nameserver $DNS1"
    [ -z "$DNS2" ]   || echo "nameserver $DNS2"
    [ -z "$SEARCH" ] || echo "search $SEARCH"
  ) > $RESOLV
}

function hostname_config()
{
   if [ -f /etc/hostname ]; then
     HOSTNAME=$(cat /etc/hostname)
   fi
   HOSTNAME=`inputbox "Enter this systems host name" "$HOSTNAME"`
   if [ -n "$HOSTNAME" ]; then
     echo "$HOSTNAME" > /etc/hostname
   else
     rm /etc/hostname
   fi
   if [ -f /etc/domainname ]; then
     DOMAINNAME=$(cat /etc/domainname)
   fi
   DOMAINNAME=`inputbox "Enter this systems domain name" "$DOMAINNAME"`
   if [ -n "$DOMAINNAME" ]; then
     echo "$DOMAINNAME" > /etc/domainname
   else
     rm /etc/domainname
   fi

   # and set them too:
   clear
   /etc/init.d/hostname
   sleep 2
}

function gateway_config() {
   GATEWAY_PROMPT="Enter Gateway IP Address"
   GATEWAY=$(cat /etc/config.d/gateway)
   GATEWAY=`inputbox "$GATEWAY_PROMPT" "$GATEWAY"`
   echo "$GATEWAY" > /etc/config.d/gateway
}

function ethernet_menu() {
    PROMPT="Actions for interface $1\nDevice is: `get_dev_status $1`"
    COMMAND=`$DIALOG  --title "Modify device $1"     \
                      --ok-label "Select"            \
		      --cancel-label "Exit"          \
                      --menu                         \
		      $PROMPT                        \
                      0 0 0                          \
                      'C'  'Reconfigure'             \
                      'M'  'Manage'                  \
		      'D'  'Delete'`

    if [ $? != 0 ] ; then
      return
    fi

    case  $COMMAND  in
      C)      ethernet_config $1;;
      M)      ethernet_manage_device $1;;
      D)      if confirm "Are you sure you wish to delete $1?" "--defaultno"; then rm -f "$CONFIG_DIR/$1"; fi;;
    esac
}

function ethernet_manage_menu() {
  while true; do
    unset LIST INTERFACES
    COUNTER=0
    for DEVICE in `get_dev_list`; do
	INTERFACES[$COUNTER]=$DEVICE
        STATUS=`get_dev_status $DEVICE`
	if [ -z "$LIST" ]; then
	  LIST="$COUNTER\n$DEVICE     $STATUS\n"
	else
	  LIST="$LIST$COUNTER\n$DEVICE     $STATUS\n"
	fi
	(( COUNTER++ ))
    done

    PROMPT="Select an interface to manage"
    DEVICE=`$DIALOG  --title "Manage Devices"       \
		     --ok-label "Select"            \
		     --cancel-label "Return"        \
		     --menu                         \
		     $PROMPT                        \
		     0 0 0                          \
		     $(echo -en $LIST)`

    case  $?  in
      0)      ethernet_manage_device ${INTERFACES[$DEVICE]} ;;
      1)      return ;;
    esac
  done
}

function ethernet_manage_device() {

    if [ ! -z $1 ]; then
        . $CONFIG_DIR/$1
    fi

    WIRELESS_MOD_PROMPT="You currently do not have the wireless tools installed required for wireless network devices.\n\nTo install these run the command:\n\n  'lin wireless_tools'\n\nYou will not be able to use this device until the module is installed."
    DHCP_TIMEOUT="If your device uses DHCP, starting a device may take an excessive amount of time if no DHCP servers are available to give an IP address.\nYou may need wait for the device to timeout if this is the case."
    ACTION_FAILED="The actions you asked to be performed have failed. You may need to check your device configuration."

    if ( [ -n "$WIRELESS_MODE" ] || [ -n "$WIRELESS_KEY" ] || [ -n "$WIRELESS_RATE" ] || [ -n "$WIRELESS_ESSID" ] && ! module_installed wireless_tools ); then
        msgbox "Warning" "$WIRELESS_MOD_PROMPT" 15
        return
    fi

  while true; do
    STATUS=`get_dev_status $1`
    if [[ "$STATUS" == "[_UP_]" ]]; then
        TOGGLE="Stop"
    else
        TOGGLE="Start"
    fi

    PROMPT="Device $1 is: $STATUS"
    COMMAND=`$DIALOG  --title "Manage Device $1"     \
		      --cancel-label "Return"        \
                      --menu                         \
		      $PROMPT                        \
                      0 0 0                          \
		      "S" "$TOGGLE Device"           \
		      "R" "Restart Device"`

    if [ $? != 0 ] ; then
      return
    fi

    $DIALOG --infobox "$DHCP_TIMEOUT" 0 0

    case  $COMMAND  in
      S)      /etc/init.d/network `echo $TOGGLE | tr 'S' 's'` "$1" ;;
      R)      /etc/init.d/network restart "$1" ;;
    esac

    if [[ "$(/sbin/ifconfig | grep $1 | wc -l)" -ge "1" ]]; then
        T=1; else T=0
    fi

    if [[ ( "$COMMAND" == "S" && "$TOGGLE" == "Start" && "$T" != "1" ) || 
          ( "$COMMAND" == "S" && "$TOGGLE" == "Stop" && "$T" != "0" ) || 
          ( "$COMMAND" == "R" && "$T" == "0" )]]; then
      msgbox "Warning" "$ACTION_FAILED" 7
    fi
  done
}

function ethernet_config()  {
# unset all variables
unset WIRELESS DEVICE AUTO MODULE  MODULE_OPTIONS ADDRESS
unset NETMASK BROADCAST GATEWAY DHCP_CLIENT DHCP_OPTIONS AUTO_OPT
unset WIRELESS_KEY WIRELESS_RATE WIRELESS_MODE WIRELESS_ESSID DHCP
unset DHCP_OPT WIRELESS_OPT WIRELESS_OPT2 IP


if [ ! -z $1 ]; then
   . $CONFIG_DIR/$1
fi;

         AUTO_PROMPT="Should this interface be activated on boot (for PCMCIA select NO)?"
         DHCP_PROMPT="Will you require DHCP?"
  DHCP_CLIENT_PROMPT="Which DHCP client do you want to use?"
 DHCP_OPTIONS_PROMPT="What options do you need to pass to your DHCP client (press return for none)?"
       DEVICE_PROMPT="For more then one device, use the menu for each of them, ie: eth0, eth1 etc.."
     WIRELESS_PROMPT="Is this a wireless device?"
 WIRELESS_MOD_PROMPT="You currently do not have the wireless tools installed required for wireless network devices.\n\nTo install these run the command:\n\n  'lin wireless_tools'\n\nYou will not be able to use this device until the module is installed."
           IP_PROMPT="Enter IP Address"
      NETMASK_PROMPT="Enter Netmask"
    BROADCAST_PROMPT="Enter Broadcast IP Address"
  IFCONF_OPTS_PROMPT="Enter extra options passed to ifconfig"
       MODULE_PROMPT="Optionally, enter the NIC kernel module to load, but leave off the .o"
  MODULE_OPTS_PROMPT="Optionally, enter the NIC module parameters"
 WIRELESS_KEY_PROMPT="What is the encryption key used? prefix with s: if ASCII, press return if NONE"
WIRELESS_RATE_PROMPT="What rate should be used (e.g. 11M or press return for auto)?"
WIRELESS_MODE_PROMPT="What mode should be used (Managed or Ad-Hoc)?"
 WIRELESS_ESS_PROMPT="What is the ESSID or network name (return for auto)?"
        ROUTE_PROMPT="If needed add route declarations. Leave blank if you don't need any. The path to 'route' itself will be added automatcally and you also don't need to specify 'route' itself. 'add' entries will be replace with 'del' entries and undone in the reverse order when the interface is shutdown."
 DHCP_MODULE_MESSAGE="The DHCP client you have chosen is not installed. Before your device will work, you will need to install the following module: "

if [ -z $1 ]; then
     while [ -z $DEVICE ]; do
         DEVICES=`get_dev_list`
         TDEV="eth0"
         for N in `seq 0 9`; do
           if [ -z `echo $DEVICES | grep "eth${N}"` ]; then
             TDEV="eth$N"
             break
           fi
         done
         DEVICE=`inputbox  "$DEVICE_PROMPT"    "$TDEV"`
     done;
else
	 DEVICE=$1
fi;

         MODULE=`inputbox  "$MODULE_PROMPT"    "$MODULE"`            &&
 MODULE_OPTIONS=`inputbox  "$MODULE_OPTS_PROMPT" "$MODULE_OPTIONS"`  &&

  if ( [ ! -z $WIRELESS_MODE ] || [ ! -z $WIRELESS_KEY ] || [ ! -z $WIRELESS_RATE ] || [ ! -z $WIRELESS_ESSID ] ); then
       WIRELESS_OPT=""
  else
       WIRELESS_OPT="--defaultno"
  fi;

  if confirm "$WIRELESS_PROMPT" "$WIRELESS_OPT" ; then
          WIRELESS="Y"
          if ! module_installed wireless_tools; then
              msgbox "Warning" $WIRELESS_MOD_PROMPT 15
          fi
          WIRELESS_KEY=`inputbox  "$WIRELESS_KEY_PROMPT" "$WIRELESS_KEY"`             &&
	  if [ ! -z $WIRELESS_MODE ]; then
	      WIRELESS_OPT2="--default-item $WIRELESS_MODE";
	  fi;

          WIRELESS_MODE=`$DIALOG   $WIRELESS_OPT2 --no-cancel --title  "Wireless Modes"           \
                                   --menu                              \
                                   "$WIRELESS_MODE_PROMPT"             \
                                   0 0 0                               \
                                   "Managed"  ""                       \
                                   "Ad-Hoc"   ""  `                    &&

          WIRELESS_RATE=`inputbox  "$WIRELESS_RATE_PROMPT" "$WIRELESS_RATE"`            &&
         WIRELESS_ESSID=`inputbox  "$WIRELESS_ESS_PROMPT" "$WIRELESS_ESSID"` 
  else
         unset WIRELESS_KEY WIRELESS_MODE WIRELESS_RATE WIRELESS_ESSID
  fi;

  case $ADDRESS in
     [dD][hH][cC][pP]) DHCP_OPT="" ;;
     *) DHCP_OPT="--defaultno" ;;
  esac;

  if  confirm  "$DHCP_PROMPT" "$DHCP_OPT" ;  then
       unset ADDRESS NETMASK GATEWAY BROADCAST

       DHCP_CLIENT=`$DIALOG  --no-cancel --title  "$TITLE"   \
                             --menu                          \
                             "$DHCP_CLIENT_PROMPT"           \
                             0 0 0                           \
                             "dhcpcd"    ""                  \
                             "dhclient"  ""                  \
                             "udhcpc"    "" `                &&

       case $DHCP_CLIENT in
          dhclient)
             if ! module_installed dhcp; then
                msgbox "Warning" "$DHCP_MODULE_MESSAGE dhcp" 10
             fi ;;
          udhcpc)
             if ! module_installed udhcp; then
                msgbox "Warning" "$DHCP_MODULE_MESSAGE udhcp" 10
             fi ;;
       esac

       DHCP_OPTIONS=`inputbox  "$DHCP_OPTIONS_PROMPT" "$DHCP_OPTIONS"`  
       ADDRESS=dhcp
  else
  		unset DHCP_CLIENT DHCP_OPTIONS
  		if [ -z $DHCP_OPT ]; then ADDRESS="10.0.0.1"; fi;
  		if [ -z $ADDRESS ]; then ADDRESS="10.0.0.1"; fi;
	while [ -z $IP ]; do
              IP=`inputbox  "$IP_PROMPT"            "$ADDRESS"`           
        done;
	        if [ -z $NETMASK ]; then NETMASK="255.255.255.0"; fi;
         NETMASK=`inputbox  "$NETMASK_PROMPT"       "$NETMASK"`      
	        if [ -z $BROADCAST ]; then BROADCAST="${IP%.*}.255"; fi;
       BROADCAST=`inputbox  "$BROADCAST_PROMPT"     "$BROADCAST"`       
                if [ -z $GATEWAY ]; then GATEWAY="${IP%.*}.1"; fi;
     IFCONF_OPTS=`inputbox  "$IFCONF_OPTS_PROMPT"   "$IFCONF_OPTS"`

         ADDRESS=$IP

  fi;

  # start by default?
  case $AUTO in
    [^yY])
      AUTO_OPT="--defaultno"
    ;;
  esac
   
  if confirm "$AUTO_PROMPT" $AUTO_OPT; then 
    AUTO="Y" 
  else
    AUTO="N"
  fi

  # add routing options?
  ROUTE_1=`inputbox "$ROUTE_PROMPT" "$ROUTE_1"`
  if [ -n "$ROUTE_1" ] ; then
    ROUTE_2=`inputbox "$ROUTE_PROMPT" "$ROUTE_2"`
    if [ -n "$ROUTE_2" ] ; then
      ROUTE_3=`inputbox "$ROUTE_PROMPT" "$ROUTE_3"`
      if [ -n "$ROUTE_3" ] ; then
        ROUTE_4=`inputbox "$ROUTE_PROMPT" "$ROUTE_4"`
      else
        unset ROUTE_4
      fi
    else
      unset ROUTE_3 ROUTE_4
    fi
  else
    unset ROUTE_2 ROUTE_3 ROUTE_4
  fi

  OUT_TO=$CONFIG_DIR/$DEVICE
  cp -p $OUT_TO /tmp/lnet.$DEVICE
  cat > $OUT_TO << EOF
AUTO=$AUTO
MODULE=$MODULE
MODULE_OPTIONS=$MODULE_OPTIONS

WIRELESS=$WIRELESS
WIRELESS_KEY=$WIRELESS_KEY
WIRELESS_RATE=$WIRELESS_RATE
WIRELESS_MODE="$WIRELESS_MODE"
WIRELESS_ESSID="$WIRELESS_ESSID"

ADDRESS=$ADDRESS
NETMASK=$NETMASK
BROADCAST=$BROADCAST
IFCONF_OPTS="$IFCONF_OPTS"

DHCP_CLIENT=$DHCP_CLIENT
DHCP_OPTIONS="$DHCP_OPTIONS"

ROUTE_1="$ROUTE_1"
ROUTE_2="$ROUTE_2"
ROUTE_3="$ROUTE_3"
ROUTE_4="$ROUTE_4"
EOF

}

. /etc/lunar/config

root_check

export IFS="$TAB_ENTER_IFS"
DIALOG="dialog
--backtitle
Lunar Network Management Utility
--stdout"

trap catch_sig INT
trap ":" QUIT

main
