#!/bin/sh
#(c) copyright Barry Kauler 2004 www.puppylinux.org
#Puppy ethernet network setup script.
#I got some bits of code from:
# trivial-net-setup, by Seth David Schoen <schoen@linuxcare.com> (c)2002
# and the little executables and, or, dotquad from the
# lnx-bbx Linux project. ipcalc app from Redhat 7.
# Thanks to GuestToo and other guys on the Puppy Forum for bug finding.
# Rarsa (Raul Suarez) reorganized the code and cleaned up the user interface

CURDIR="`pwd`"
APPDIR=`dirname "$0"`
cd "${APPDIR}"
APPDIR="`pwd`"
cd "${CURDIR}"


#================================================================================
#============= FUNCTIONS USED IN THE SCRIPT ==============
#================================================================================
. ${APPDIR}/wag-profiles.sh

showMainWindow()
{
	while [ "$MAIN_RESPONSE" != "19" ] && [ "$MAIN_RESPONSE" != "abort" ]
	do

		buildMainWindow

		I=$IFS; IFS=""
		for STATEMENTS in  $(gtkdialog --program Puppy_Network_Setup); do
			eval $STATEMENTS
		done
		IFS=$I

		MAIN_RESPONSE=${EXIT}

		INTERFACE=`echo $EXIT | grep "Interface_" | cut -d_ -f 2`

		[ ! -z ${INTERFACE} ] &&	MAIN_RESPONSE=13

		case $MAIN_RESPONSE in
			10) showLoadModuleWindow ;;
			17) saveNewModule ;;
			18) unloadNewModule ;;
			13) showConfigureInterfaceWindow ${INTERFACE} ;;
			21) showHelp  ;;
		esac

	done

} # end of showMainWindow


#================================================================================
refreshMainWindowInfo ()
{
	findLoadedModules

  #we need to know what ethernet interfaces are there...
  INTERFACE_NUM=`ifconfig -a | grep "Link encap:Ethernet" | wc -l | awk '{print $1}'`
  INTERFACES="`ifconfig -a | grep "Link encap:Ethernet" | cut -f 1 -d " " | tr "\n" " "`"
  INTERFACEBUTTONS=""

  for INTERFACE in ${INTERFACES}
  do
    INTERFACEBUTTONS="
			${INTERFACEBUTTONS}
			<button>
				<label>${INTERFACE}</label>
				<action>EXIT=Interface_${INTERFACE}</action>
			</button>"
  done

  LOADEDETH=`cat /tmp/loadedeth.txt | tr "\n" " "`

  if [ $INTERFACE_NUM -eq 0 ];then
    echo "Puppy does not see any active ethernet interfaces.

If you have one or more ethernet cards (interfaces) in the PC and you want
to use them, then driver modules will have to be loaded. This is supposed to be
autodetected and the correct driver loaded when Puppy boots up, but it hasn't
happened in this case. Never mind, you can do it manually!" > /tmp/net-setup_MSGINTERFACES.txt

  fi
  if [ $INTERFACE_NUM -eq 1 ];then
    echo "Puppy sees $INTERFACE_NUM active ethernet interface, that is, actually responding
even if it is not yet doing what you want!.
To test or configure the interface, click on the corresponding
interface button."  > /tmp/net-setup_MSGINTERFACES.txt
  fi
  if [ $INTERFACE_NUM -gt 1 ];then
    echo "Puppy sees $INTERFACE_NUM active ethernet interfaces , that is, actually responding
even if they are not yet doing what you want!.
To test or configure an interface, click on the corresponding interface button."  > /tmp/net-setup_MSGINTERFACES.txt
  fi

	echo "Puppy has done a quick check to see what ethernet driver modules are currently
loaded. Here they are:
 ${LOADEDETH}" > /tmp/net-setup_MSGMODULES.txt

} # end refreshMainWindowInfo

#================================================================================
buildMainWindow ()
{
	echo "${TOPMSG}" > /tmp/net-setup_TOPMSG.txt


	export Puppy_Network_Setup="
		<vbox>
			<text><label>\"`cat /tmp/net-setup_TOPMSG.txt`\"</label></text>
			<frame Driver Modules>
				<text><label>\"`cat /tmp/net-setup_MSGMODULES.txt`\"</label></text>
				${MODULEBUTTONS}
			</frame>
			<frame Interfaces>
				<hbox>
				<text><label>\"`cat /tmp/net-setup_MSGINTERFACES.txt`\"</label></text>
				<vbox>
					<text><label>\" \"</label></text>
					<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
					${INTERFACEBUTTONS}
				</vbox>
				</hbox>
			</frame>
			<hbox>
				<vbox>
					<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
					<button><label>Help</label><action>Exit=21</action></button>
				</vbox>
				<vbox>
					<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
					<button><label>Exit</label><action>Exit=19</action></button>
				</vbox>
			</hbox>
		</vbox>"
}

#================================================================================
showLoadModuleWindow()
{
	echo -n "" > /tmp/ethmoduleyesload.txt
	MODULELIST=`cat /etc/networkmodules | sort | tr "\n" " "`

	echo "Xdialog --left --wmclass \"etherwiz\" --title \"Puppy Ethernet Wizard\" --stdout \
	 --menubox \"This is the hardware in your PC that seems to be an ethernet interface:
`cat /proc/pci | grep -i "ether" | cut -d: -f 2`
    (Note, USB and PCMCIA ethernet hardware is not shown above, only PCI.)

And these are the driver modules already loaded:
${LOADEDETH}

Choose auto-probe, custom driver, or driver from list.\nNote, the custom choice allows you to enter a module name followed by optional\nparameters. For ISA cards, this may be mandatory.\nExample1: ne io=0x000, Example1: arlan  io=0x300 irq=11\n(Example1 works for most ISA cards and does some autoprobing of io and irq) \" 0 0 9 \
	 auto \"AUTO PROBE ALL DRIVERS\" \
	 specify \"SPECIFY A CUSTOM DRIVER\" \
	 $MODULELIST 2> /dev/null" > /tmp/net-setup-modulelist.sh

	LOADMODULE_RESPONSE="`sh /tmp/net-setup-modulelist.sh`"

  case "${LOADMODULE_RESPONSE}" in
    "")
			TOPMSG="REPORT ON LOADING OF MODULE: No module was loaded" ;;
    "auto")
			autoLoadModule ;;
    "specify")
			loadSpecificModule ;;
    *)
			tryLoadModule ${LOADMODULE_RESPONSE} ;;
  esac

  NEWLOADED="`cat /tmp/ethmoduleyesload.txt`"
  NEWLOADf1="`echo -n "$NEWLOADED" | cut -f 1 -d " "`" #remove any extra params.
  if [ "${NEWLOADED}" ];then
		refreshMainWindowInfo

    TOPMSG="REPORT ON LOADING OF MODULE: Module '$NEWLOADf1' successfully loaded"
    MODULEBUTTONS="
					<hbox>
					<text><label>\"
If you can see a new active interface showing up above click the 'Save'
button and proceed to configure the interface. The 'Save' will save the
selection so that Puppy will automatically load $NEWLOADf1 at bootup.\"</label></text>
						<vbox>
							<text><label>\" \"</label></text>
							<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
							<button><label>Save</label><action>EXIT=17</action></button>
						</vbox>
					</hbox>
					<hbox>
					<text><label>\"
If you cannot see a new active interface showing up above, it means that
the interface is not recognized by the newly loaded module. Click the
'Unload' button and try to load another module. The 'Unload', will unload
the module as well as forget about loading it at bootup.\"</label></text>
						<vbox>
							<text><label>\" \"</label></text>
							<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
							<button><label>Unload</label><action>EXIT=18</action></button>
						</vbox>
					</hbox>"
    else
      BGCOLOR="#ffc0c0"
      TOPMSG="REPORT ON LOADING OF MODULE: No module was loaded"
    fi
} # end of showLoadModuleWindow

#================================================================================
tryLoadModule ()
{
	MODULE_NAME=$1
	if modprobe ${MODULE_NAME}
	then
		Xdialog --left --wrap --stdout --title "Puppy Ethernet Wizard: hardware" --msgbox "Module ${MODULE_NAME} has loaded successfully.\nThat does not mean it will actually work though!\nAfter clicking OK, back on the main window if you see a new active interface\nproceed to configure it." 0 0
		echo -n "${MODULE_NAME}" > /tmp/ethmoduleyesload.txt
	else
		Xdialog --stdout --msgbox "Loading ${MODULE_NAME} failed; try a different driver." 0 0
	fi
} # end tryLoadModule

#================================================================================
loadSpecificModule ()
{
	RESPONSE=$(Xdialog --stdout --title "Puppy Ethernet Wizard: hardware" --inputbox "Please type the name of a specific module to load\n(extra parameters allowed, but don't type tab chars)." 0 0 mymodule 2> /dev/null)
	if [ $? -eq 0 ];then
		tryLoadModule ${RESPONSE}
	fi
} # end loadSpecificModule

#================================================================================
autoLoadModule ()
{
	#this is the autoloading...
	SOMETHINGWORKED=false
	#clear
	for CANDIDATE in $PCIMODULES
	do

		#if have pcmcia, do not try loading the others...
		MDOIT="no"
		echo "$CANDIDATE" | grep "_cs"
		if [ $? -eq 0 ];then #=0 found.
			if [ "$MPCMCIA" = "yes" ];then
				MDOIT="yes"
			fi
		else
			if [ ! "$MPCMCIA" = "yes" ];then
				MDOIT="yes"
			fi
		fi

		#also, do not try if it is already loaded...?
		cat /tmp/loadedeth.txt | grep "$CANDIDATE"
		if [ $? -eq 0 ];then
			MDOIT="no"
		fi

		#in case of false-hits, ignore anything already tried this session...
		cat /tmp/logethtries.txt | grep $CANDIDATE
		if [ $? -eq 0 ];then #=0 found.
			MDOIT="no"
		fi

		if [ "$MDOIT" = "yes" ];then
			echo; echo "*** Trying $CANDIDATE."
			if modprobe $CANDIDATE
			then
				SOMETHINGWORKED=true
				WHATWORKED=$CANDIDATE
				#add it to the log for this session...
				echo "$CANDIDATE" >> /tmp/logethtries.txt
				break
			fi
		fi

	done
	sleep 2
	if $SOMETHINGWORKED
	then
		Xdialog --left --wrap --msgbox "Success loading the $WHATWORKED module. That does not mean it will actually work though!\nAfter clicking OK, back on the main window if you see a new active interface\nproceed to configure it.\n\nNOTE: it is possible that a module loads ok, but it is a false hit, that is, does\nnot actually work with your network card. In that case, try autoprobing again. This\nscript will remember the previous attempts (until you exit this script) and will\njump over them.\nIf you do get false hits, let us know about it on the Puppy Discussion Forum!" 0 0
		echo -n "$WHATWORKED" > /tmp/ethmoduleyesload.txt
	else
		MALREADY="`cat /tmp/loadedeth.txt`"
		Xdialog --msgbox "No module loaded successfully.\n\nNote however that these modules are already loaded:\n${MALREADY}" 0 0
		return 1
	fi
} # end autoLoadModule

#================================================================================
findLoadedModules ()
{
  echo -n " " > /tmp/loadedeth.txt

  ALL_MOD=`lsmod | cut -f 1 -d " "`

	COUNT_MOD=0
  for MOD in $ALL_MOD
  do
		COUNT_MOD=`expr $COUNT_MOD + 1`
  done

	(
		for MOD in $ALL_MOD
		do
			echo "X"
			echo "$PCIMODULES" | grep -E "^${MOD}$" >> /tmp/loadedeth.txt
			if [ $? -eq 0 ];then
			 echo -n " " >> /tmp/loadedeth.txt #space separation
			fi
		done
  ) | Xdialog --title "Puppy Ethernet Wizard" --progress "Checking loaded modules" 0 0 $COUNT_MOD

} # end of findLoadedModules

#================================================================================
testInterface()
{
  INTERFACE=$1

	(
		UNPLUGGED="false"
		ifconfig $INTERFACE | grep " UP " > /dev/null
		if [ ! $? -eq 0 ];then #=0 if found
			ifconfig $INTERFACE up
		fi
		#BK1.0.7 improved link-beat detection...
		echo "X"
		if [ "`ifplugstatus ${INTERFACE} | grep "link beat detected"`" = "" ];then
			sleep 2
			echo "X"
			if [ "`ifplugstatus-0.25 ${INTERFACE} | grep "link beat detected"`" = "" ];then
				sleep 2
				echo "X"
				if [ "`ifplugstatus ${INTERFACE} | grep "link beat detected"`" = "" ];then
					sleep 2
					echo "X"
					if [ "`ifplugstatus-0.25 ${INTERFACE} | grep "link beat detected"`" = "" ];then
						UNPLUGGED="true"
					fi
				fi
			fi
		fi
		echo "${UNPLUGGED}" > /tmp/net-setup_UNPLUGGED.txt
  ) | Xdialog --title "Puppy Ethernet Wizard" --progress "Testing Interface ${INTERFACE}" 0 0 4

  UNPLUGGED=$(cat /tmp/net-setup_UNPLUGGED.txt)

  if [ "$UNPLUGGED" != "false" ];then #BK1.0.7
    #no cable plugged in, no network connection possible...
    ifconfig $INTERFACE down
    BGCOLOR="#ffc0c0"
    if [ ${IS_WIRELESS} ] ; then
      TOPMSG="REPORT ON TEST OF $INTERFACE CONNECTION:
'Unable to connect to a wireless network'

Verify that the wireless network is available and
that you have provided the correct wireless parameters."
    else
      TOPMSG="REPORT ON TEST OF $INTERFACE CONNECTION:
'Unable to connect to the network'

Verify that the network is available and
that the ethernet cable is plugged in."
    RETTEST=1
    fi
  else
    BGCOLOR="#e0ffe0"
    TOPMSG="REPORT ON TEST OF $INTERFACE CONNECTION:
'Puppy was able to find an alive network'

You can proceed to acquire an IP address."
		RETTEST=0
  fi

  return ${RETTEST}
} # end of testInterface

#================================================================================
showConfigureInterfaceWindow()
{
  INTERFACE=$1

  initializeConfigureInterfaceWindow

  RETVALUE=""
  # 1=Close window 19=Back Button 22=Save configuration
  while [ "$RETVALUE" != "1" ] && [ "$RETVALUE" != "19" ] && [ "$RETVALUE" != "22" ]
  do

    buildConfigureInterfaceWindow

    I=$IFS; IFS=""
    for STATEMENTS in  $(gtkdialog --program Puppy_Network_Setup); do
      eval $STATEMENTS
    done
    IFS=$I

    RETVALUE=${EXIT}
    [ ! "${RETVALUE}" != "abort" ] &&	RETVALUE=1

    RETSETUP=99
    case $RETVALUE in
       1 | 19) # close window
          TOPMSG="NETWORK CONFIGURATION OF $INTERFACE CANCELED!
Try again, or click 'Exit' to give up for now."
          ;;
      10) # AutoDHCP
          dhcpSetup
          RETSETUP=$?
          ;;
      11) # StaticIP
          manualSetup
          RETSETUP=$?
          ;;
      13) # Test
          testInterface ${INTERFACE}
          RETSETUP=$?
          ;;
      14) # Wireless
          configureWireless ${INTERFACE}
          ;;
      21) # Help
          showHelp
          ;;
    esac

    if [ $RETVALUE -eq 10 ] || [ $RETVALUE -eq 11 ] ; then
      if [ $RETSETUP -ne 0 ] ; then
        TOPMSG="NETWORK CONFIGURATION OF $INTERFACE UNSUCCESSFUL!
Try again, or click 'Back' to give up for now."
      else
        RETVALUE=1
        Xdialog --yesno "NETWORK CONFIGURATION OF $INTERFACE SUCCESSFUL!

Do you want to save this configuration?

If you want to keep this configuration for next boot: click 'Yes'.
If you just want to use this configuration for this session: click 'No'." 0 0
		if [ $? -eq 0 ] ; then
          saveInterfaceSetup ${INTERFACE}
          TOPMSG="NETWORK CONFIGURATION OF $INTERFACE SUCCESSFUL!
The configuration has been saved to file /etc/${INTERFACE}mode.
This file is read at bootup by /etc/rc.d/rc.network

If there are no more interfaces to setup and configure, just click 'Exit' to get out."
        else
          TOPMSG="NETWORK CONFIGURATION OF $INTERFACE SUCCESSFUL!
The configuration was not saved for next boot.

If there are no more interfaces to setup and configure, just click 'Exit' to get out."
        fi
      fi
    fi

  done

} # end showConfigureInterfaceWindow

#================================================================================
buildConfigureInterfaceWindow ()
{
	export Puppy_Network_Setup="
		<vbox>
			<frame Configure ${INTERFACE}>
				<text><label>\"${TOPMSG}\"</label></text>
				${WIRELESSSECTION}
				<hbox>
					<text><label>\"${TESTMSG}\"</label></text>
					<vbox>
						<text><label>\" \"</label></text>
						<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
						<button><label>Test ${INTERFACE}</label><action>Exit=13</action></button>
					</vbox>
				</hbox>
				<hbox>
					<text><label>\"${DHCPMSG}\"</label></text>
					<vbox>
						<text><label>\" \"</label></text>
						<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
						<button><label>Auto DHCP</label><action>Exit=10</action></button>
					</vbox>
				</hbox>
				<hbox>
					<text><label>\"${STATICMSG}\"</label></text>
					<vbox>
						<text><label>\" \"</label></text>
						<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
						<button><label>Static IP</label><action>Exit=11</action></button>
					</vbox>
				</hbox>
			</frame>
			<hbox>
				<vbox>
					<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
					<button><label>Help</label><action>Exit=21</action></button>
				</vbox>
				${SAVE_SETUP_BUTTON}
				<vbox>
					<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
					<button><label>Back</label><action>Exit=19</action></button>
				</vbox>
			</hbox>
		</vbox>"
}

#================================================================================
initializeConfigureInterfaceWindow ()
{
	TOPMSG="OK, let's try to configure ${INTERFACE}."

	TESTMSG="
Make sure that your ${INTERFACE} interface is connected into an 'alive'
network by clicking on the 'Test' button.
After you confirm that, you can configure the interface."

	DHCPMSG="
The absolutely easiest way to configure the network is to be on
a LAN that has a DHCP server. This will enable Puppy to
query the server at bootup and automatically be assigned an IP
address. The'dhcpcd' client daemon program is launched and
network access happens automatically."

	STATICMSG="
If a DHCP server is not available, you will have to do everything
manually by setting a static IP, but this script will make it easy
(I would like to thank the guys at the LNX-BBC Linux project,
 whose 'trivial-net-setup' script helped me enormously here)."

	checkIfIsWireless ${INTERFACE}

	if [ ${IS_WIRELESS} ] ; then
		WIRELESSSECTION="
					<hbox>
						<text><label>\"
Puppy found that ${INTERFACE} is a wireless interface.
If you want to conect using a wireless network, you must set the
wireless parameters before trying to configure it either with
DHCP or Static IP.\"</label></text>
						<vbox>
							<text><label>\" \"</label></text>
							<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
							<button><label>Wireless</label><action>Exit=14</action></button>
						</vbox>
					</hbox>
					"
	else
		WIRELESSSECTION=""
	fi
	SAVE_SETUP_BUTTON=""
}

#================================================================================
checkIfIsWireless ()
{
  INTERFACE=$1
  IS_WIRELESS=""

	cat /proc/net/wireless | grep -q "${INTERFACE}"
	[ $? -eq 0 ] && IS_WIRELESS="true"
}

#================================================================================
configureWireless()
{
	INTERFACE=$1
	showProfilesWindow ${INTERFACE}
	if [ $? -eq 0 ] ; then
		testInterface ${INTERFACE}
	else
		TOPMSG="WIRELESS CONFIGURATION OF $INTERFACE CANCELED!
To connect to a wireless network you have to select a profile to use'. "
	fi
}

#================================================================================
dhcpSetup()
{
	ifconfig ${INTERFACE} down
	{
		if ps wax | grep dhcpcd | grep "$INTERFACE" >/dev/null
		then
			# Must kill old dhcpcd first
			dhcpcd -k "$INTERFACE"
			rm /etc/dhcpc/dhcpcd-${INTERFACE}.pid 2>/dev/null #if left over from last session, causes trouble.
			rm /etc/dhcpc/dhcpcd-${INTERFACE}.cache 2>/dev/null #ditto
			rm /etc/dhcpc/dhcpcd-${INTERFACE}.info 2>/dev/null #ditto
		fi
		sleep 1
		rm -f /etc/dhcpc/dhcpcd-${INTERFACE}.pid
		if dhcpcd -d "$INTERFACE"
		then
#			echo -n "auto" > /etc/${INTERFACE}mode
			HAS_ERROR=0
		else
#			rm -f /etc/${INTERFACE}mode
			HAS_ERROR=1
		fi
		echo "${HAS_ERROR}" > /tmp/net-setup_HAS_ERROR.txt
		echo "XXXX"
	} | Xdialog --no-buttons --title "Puppy Ethernet Wizard: DHCP" --infobox "There may be a delay of up to 60 seconds while Puppy waits for the
DHCP server to respond. Please wait patiently..." 0 0 0

  HAS_ERROR=$(cat /tmp/net-setup_HAS_ERROR.txt)

  if [ ${HAS_ERROR} -eq 0 ]
  then
    MODECOMMANDS="
echo \"Trying to get IP address from DHCP server (60sec timeout)...\"
rm /etc/dhcpc/dhcpcd-${INTERFACE}.pid 2>/dev/null #if left over from last session, causes trouble.
rm /etc/dhcpc/dhcpcd-${INTERFACE}.cache 2>/dev/null #ditto
rm /etc/dhcpc/dhcpcd-${INTERFACE}.info 2>/dev/null #ditto
dhcpcd ${INTERFACE}
"
  else
    MODECOMMANDS=""
  fi

	return ${HAS_ERROR}
} #end of dhcpSetup

#================================================================================
manualSetup()
{

  Xdialog --center --wrap --title "Puppy Ethernet Wizard: Static IP" --msgbox "Configuring manually...\n\nIn the questions that follow, please enter all addresses in dotted-quad format (a.b.c.d)\nother formats will not be recognized." 0 0
  while true
  do
    readaddr "Enter your IP address (e.g. 216.88.157.147): "
    if [ ! $? -eq 0 ];then
      return 1
    fi
    IP="$RESULT"
    DEFAULTMASK=$(ipcalc --netmask "$IP" | cut -d= -f2)
    while [ -z "$NETMASK" ]
    do
      readaddr "Enter your netmask: " $DEFAULTMASK
      if [ ! $? -eq 0 ];then
        return 1
      fi

      if [ "x$RESPONSE" = x ];then
        NETMASK="$DEFAULTMASK"
      else
        if validip "$RESPONSE"	# This is wrong, because not all valid IP
				# addresses are valid netmasks.  But we can
				# catch some inconsistencies below.
        then
          NETMASK="$RESPONSE"
        else
          Xdialog --center --title "Puppy Ethernet Wizard: Static IP" --msgbox "Invalid entry, try again." 0 0
        fi
      fi
    done

    BROADCAST=$(ipcalc -b $IP $NETMASK | cut -d= -f2)

    unset GATEWAY
    GATEWAYOK=false
    until $GATEWAYOK
    do
      unset RESULT
      readaddr_blankok "
Enter your default router (gateway) address (Enter for none):

Note that if you won't specify a gateway you will have access
your local-area network, but you'll need to add a route
manually if you want to use the Internet"
      if [ ! $? -eq 0 ];then
        return 1
      fi
      if [ -z "$RESULT" ];then
        GATEWAYOK=true
      else
        if validip "$RESULT"
        then
          GATEWAY="$RESULT"
          GATEWAYOK=true
        else
          xmessage -center -title "Puppy Ethernet Wizard: Static IP" "Invalid entry, you will have to try again."
        fi
      fi
    done

    echo "You have GATEWAY=$GATEWAY" #test

 # Now let's do the nameserver
 unset NAMESERVER
 NAMESERVEROK=false
 until $NAMESERVEROK
 do
  unset RESULT
  readaddr_blankok "Enter the IP address of a nameserver for resolving DNS names to IP addresses\n(Enter for defaults, which should usually work on the public Internet):"
  if [ ! $? -eq 0 ];then
   return 1
  fi
  if [ -z "$RESULT" ];then
   NAMESERVEROK=true
  else
   if validip "$RESULT"
   then
    NAMESERVER="$RESULT"
    NAMESERVEROK=true
   else
    xmessage -center -title "Puppy Ethernet Wizard: Static IP" "Invalid entry, you will have to try again."
   fi
  fi
 done

 # Check that network is right
 HOSTNUM=$(dotquad "$IP")
 MASKNUM=$(dotquad "$NETMASK")
 GATENUM=$(dotquad "$GATEWAY")
 CASTNUM=$(dotquad "$BROADCAST")

 HOSTNET=$(and "$MASKNUM" "$HOSTNUM")
 GATENET=$(and "$MASKNUM" "$GATENUM")

 if [ -z "$GATEWAY" ];then
  # It is legitimate not to have a gateway at all.  In that case, it
  # doesn't have a network. :-)
  unset HOSTNET
  unset GATENET
 fi

#BK: the lnx-bbc people had ifconfig $INTERFACE inet $IP netmask $NETMASK broadcast $BROADCAST up
#    but "inet" seems nonstandard. $IP is required without the "inet"...

	ifconfig ${INTERFACE} down

 CONVO=`cat <<MSG1
ifconfig ${INTERFACE} ${IP} netmask ${NETMASK} broadcast ${BROADCAST} up
`
 CONVG=`cat <<MSG2
route add -net default gw ${GATEWAY}
`
 if [ x"$HOSTNET" != x"$GATENET" ];then
  Xdialog --center --wrap --title "Puppy Ethernet Wizard: Static IP" --msgbox "Your gateway $GATEWAY is not on this network!  Please try again.\n(You may have entered your netmask incorrectly, for instance.)" 0 0  0 0
 else
  # do the work BK: see note above.
  ifconfig $INTERFACE $IP netmask $NETMASK broadcast $BROADCAST up
  if [ $? -eq 0 ];then
#   echo "$CONVO" > /etc/${INTERFACE}mode #used at bootup, see rc.network.
   MODECOMMANDS="${CONVO}"
   # Configure a nameserver, if we're supposed to.
   # This now replaces any existing resolv.conf, which
   # we will try to back up.
   if [ "$NAMESERVER" ];then
    mv -f /etc/resolv.conf /etc/resolv.conf.$$
    echo "nameserver $NAMESERVER" > /etc/resolv.conf
   fi

   # add default route, if we're supposed to
   if [ "$GATEWAY" ];then
    route add -net default gw "$GATEWAY"
    if [ $? -eq 0 ];then #0=ok.
     Xdialog --center --title "Puppy Ethernet Wizard: Static IP" --msgbox "Default route set through $GATEWAY." 0 0
#     echo "$CONVG" >> /etc/${INTERFACE}mode #used at bootup.
     MODECOMMANDS="${MODECOMMANDS}\n${CONVG}"
    else
     Xdialog --center --title "Puppy Ethernet Wizard: Static IP" --msgbox "Could not set default route through $GATEWAY.  Please try again.\n\nNote that Puppy has tried to do this:\n${CONVG}" 0 0
     ifconfig "$INTERFACE" down
     return 1
    fi
   fi

   return 0
  else
   Xdialog --center --title "Puppy Ethernet Wizard: Static IP" --msgbox "Interface configuration failed; please try again.\n\nIf configuration had succeeded, file /etc/${INTERFACE}mode would have\nbeen created, which is executed at bootup by /etc/rc.d/rc.network\nIf you really want to, you can manually create this file.\n\nWhat Puppy has just tried to do is this:\n${CONVO} \n\nIf you think that this is incorrect for your system, and you can come up\nwith something else that works, let me know and maybe I can modify this\nnetwork setup script." 0 0
   ifconfig "$INTERFACE" down
#   rm /etc/${INTERFACE}mode
   MODECOMMANDS=""
  fi
 fi

 unset NETMASK	# Must unset NETMASK in order for the user to be prompted
		# for it next time through.

done
} #end of manualSetup

#================================================================================
saveNewModule()
{
  # save newly loaded module
  cat /etc/ethernetmodules | grep "$NEWLOADED"
  if [ ! $? -eq 0 ];then
    echo "$NEWLOADED" >> /etc/ethernetmodules
  fi
  TOPMSG="MODULE '$NEWLOADED' RECORDED IN /etc/ethernetmodules
Puppy will read this when booting up."
	setDefaultMODULEBUTTONS
}


#================================================================================
unloadNewModule()
{
  # unload newly loaded module
  modprobe -r $NEWLOADED
  cat /etc/ethernetmodules | grep -v "$NEWLOADED" > /etc/ethernetmodules
  TOPMSG="MODULE '$NEWLOADED' UNLOADED.
Also, '$NEWLOADED' removed from /etc/ethernetmodules (if it was there)."

  setDefaultMODULEBUTTONS

	refreshMainWindowInfo

}

#================================================================================
validip() {
# uses dotquad.c to parse $1 as a dotted-quad IP address
if dotquad "$1" >/dev/null
then
 return 0
else
 return 1
fi
} #end of validip function

#================================================================================
readaddr() {
while true
do
 foo=$(Xdialog --center --wrap --stdout --title "Puppy Ethernet Wizard" --inputbox "$1" 0 0 $2 2>/dev/null)
 # cancel?
 if [ $? -ne 0 ];then
  return 1
 fi
 #dotquad $foo
 if validip "$foo"
 then
  if [ ! "$foo" = "216.88.157.147" ];then
   #RESULT="$foo"
   #RESPONSE="$foo"
   #return
   break
  else
   Xdialog --center --wrap --title "Puppy Ethernet Wizard: networking" --msgbox "216.88.157.147 was provided only as an example.\nPlease enter your own IP address instead!" 0 0
  fi
 fi
done
RESULT="$foo"
RESPONSE="$foo"
} #end of readaddr function

#================================================================================
readaddr_blankok() {
while true
do
 foo=$(Xdialog --center --wrap --stdout --title "Puppy Ethernet Wizard: networking" --inputbox "$1" 0 0 $2 2>/dev/null)
 # cancel?
 if [ $? -ne 0 ];then
  return 1
 fi
 if [ -z "$foo" ];then
  RESULT=""
  RESPONSE=""
  return 0
 fi
 if validip "$foo"
 then
  if [ "$foo" != "216.88.157.147" ];then
   RESULT="$foo"
   return 0
  else
   Xdialog --center --wrap --title "Puppy Ethernet Wizard: networking" --msgbox "216.88.157.147 was provided only as an example.\nPlease enter your own IP address instead!" 0 0
  fi
 fi
done
RESULT="$foo"
RESPONSE="$foo"
} #end of readaddr_blankok function

#================================================================================
setDefaultMODULEBUTTONS ()
{
  MODULEBUTTONS="
  			<hbox>
					<text><label>\"If it appears the driver module for an ethernet card isn't loaded,
click on the 'Load a driver' button.\"</label></text>
					<vbox>
						<pixmap><input file>/usr/share/pixmaps/net-setup_btnsize.png</input></pixmap>
						<button><label>Load driver</label><action>Exit=10</action></button>
					</vbox>
				</hbox>"
}


#================================================================================
saveInterfaceSetup()
{
  INTERFACE=$1

  if [ ! ${IS_WIRELESS} ] ; then
    rm -f /etc/${INTERFACE}wireless
  fi

  if [ -e "/tmp/wag-profiles_iwconfig.sh" ] ; then
    cp /tmp/wag-profiles_iwconfig.sh /etc/${INTERFACE}wireless
  fi

  echo -e "${MODECOMMANDS}" > /etc/${INTERFACE}mode

}

#================================================================================
showHelp()
{
  dillo /usr/share/doc/HOWTO-network.htm &
}


#================================================================================
#=============== START OF SCRIPT BODY ====================
#================================================================================


# Cleanup older temp files
rm -f /tmp/ethmoduleyesload.txt
rm -f /tmp/loadedeth.txt
rm -f /tmp/wag-profiles_iwconfig.sh

> /tmp/logethtries.txt

# Do we have pcmcia hardware?...
cat /proc/pci | grep -i "cardbus" > /dev/null
if [ $? -eq 0 ];then
  MPCMCIA="yes"
else
  cat /proc/pci | grep -i "pcmcia" > /dev/null
  if [ $? -eq 0 ];then
    MPCMCIA="yes"
   fi
fi
PCIMODULES=`cat /etc/networkmodules | cut -f 1 -d " "`

setDefaultMODULEBUTTONS

refreshMainWindowInfo

BGCOLOR="#ffe0e0" #light red.
TOPMSG="Hi, networking is not always easy to setup, but let's give it a go!"

MAIN_RESPONSE=""

showMainWindow

#================================================================================
#================ END OF SCRIPT BODY =====================
#================================================================================
