#!/bin/sh
#(c) Copyright Barry Kauler 2010, bkhome.org
#2010 Lesser GPL licence v2 (/usr/share/doc/legal/lgpl-2.1.txt)
#100308 first version of script, open and wep networks only.
#100309 supports wpa. 100310 bug fixes.
#100312 wireless code cleanup, bug fixes.
#100313 wpa_supplicant, try different values for ap_scan.
#100313 added support for ndiswrapper.
#100314 bugfixes.
#100320 fix if essid has spaces. Extra logging. handle special cases.
#100321 fuCNT fix. 100323 FLAGERR fix.
#100324 Start firewall, change from button to checkbox.
#100325 DHCPCDFIX option for wired.
#100405 append last 10 lines of /var/log/messages to error log.
#100413 attempt restart blinky_tray.
#100513 more delay, repeat scan attempt.
#100608 k2.6.27.47: anomaly, 'readlink /sys/class/net/$INTERFACE/device/driver' returns 'ath5k_pci' but module is 'ath5k'.
#100608 have changed most xmessage displays to yaf-splash.
#100703 extra flush seems to be needed when release interface.
#101029 fix when no wireless networks found.
#101118 bugfix, so network-disconnect works.
#110203 improve scanning.
#110505 support sudo for non-root user.
#120107 gtkdialog3 to gtkdialog4, new 'Profile' frame in main window, new profiles help window.
#120204 rodin.s: internationalized.
#120222 small change to 'connect now' button.
#120323 replace remaining 'xmessage' with 'pupmessage'.
#120324 fix syntax error gettext.
#121117 rerwin: add dropwait option to dhcpcd startup. see also rc.network.
#130221 vertical scrollbar if more than 9 wireless networks found.
#140201 peebee reports wifi disabled, need to unblock. 140217
#150925 translation fixes.
#151004 increase wireless scan delay 2 sec to 4 sec. 151008 modify sleeps.
#151101 check if kernel ndiswrapper module exists.
#160909 actual bus may differ from that in /etc/networkmodules.
#160922 fix for bus 'sdio'
#160922 precaution, IF_DRIVER should match a kernel module name.
#161022 firewall_ng is in /etc/init.d/rc.firewall when installed. 161106 fix.
#170521 sort wifi networks in order of signal strength.
#170522 write $INTERFACE to /tmp/sns_interface_success for wired interface.
#170522 test if have the old 'ifplugstatus-0.18' (as well as 'ifplugstatus').
#170522 fix delete buttons.
#170706 do not test for 'gtkdialog4'
#170706 rerwin: test for 'connectwizard_exec', set 'sns', dlg if already running.
#170706 rerwin: precaution, remove /tmp/sns_interface_success
#170706 rerwin: fix delete buttons to handle ' or " in SSID or password.
#170824 new CRD button (code from quicksetup).
#180924 need wait after starting dhcpcd. 181012 bigger sleeps for ifplugstatus.

export TEXTDOMAIN=sns___sns
export OUTPUT_CHARSET=UTF-8
. gettext.sh

[ "`whoami`" != "root" ] && exec sudo -A ${0} ${@} #110505

#170706 rerwin. ref: network_connect_update PET.
if which connectwizard_exec &>/dev/null \
  && ! connectwizard_exec sns; then
 Xdialog --left --wmclass "sns" --title "$(gettext 'Simple Network Setup')"  --backtitle "\n$(gettext 'Simple Network Setup cannot start now because it is already active.')" --icon /usr/local/lib/X11/pixmaps/error.xpm --msgbox "\n$(gettext 'Please use the active SNS session or\nterminate it and start SNS again.')\n" 0 70
 exit 1
fi

#each line of /etc/simple_network_setup/connections has everything known about a connection:
#(please ignore spaces, put here for readability only)
#Wireless:
#        1         2          3         4       5                                   6                 7           8                 9            10           11                 12         13                         14       15          16         17
#format: INTERFACE|IF_INTTYPE|IF_DRIVER|IF_BUS |IF_INFO                            |MACADDRESS       |CELL_NUMBER|CELL_ADDRESS     |CELL_CHANNEL|CELL_QUALITY|CELL_ENCRYPTIONKEY|CELL_ESSID|SEC_KEY                   |SEC_MGMT|ENCODEPROTO|WPA_DRIVER|DHCPCDFIX|
#ex:     wlan1    |Wireless  |rt73usb  |usb    |Ralink RT73 USB Wireless LAN driver|00:26:19:F5:AC:3D|01         |00:17:3F:68:33:7E|11          |70/70       |on                |belkin54g |000102030405060708090a0b0c|WEP     |           |          |
#Wired:
#        1         2          3         4       5                                       6                 7
#format: INTERFACE|IF_INTTYPE|IF_DRIVER|IF_BUS |IF_INFO                                |MACADDRESS       |DHCPCDFIX|
#ex:     eth0     |Wired     |sky2     |pci    |Marvell Yukon 2 Gigabit Ethernet driver|00:17:36:84:E5:1A|         |

##find all the interfaces...
#IF_NUM=`ifconfig -a | grep -Fc 'Link encap:Ethernet'`
#if [ $IF_NUM -eq 0 ];then
# xmessage -center -bg red "SORRY, CANNOT FIND ANY NETWORK INTERFACES"
# exit
#fi

M_close="`gettext 'Close'`"
CR='
'

#170522 test if have the old version (as well as 'ifplugstatus')...
IFPLUGSTATUS018='ifplugstatus-0.18'
if ! which ifplugstatus-0.18 >/dev/null ; then IFPLUGSTATUS018='ifplugstatus' ; fi

BIGGESTCNT=0
echo -n '' > /tmp/sns_interfaces
INTERFACES="`ifconfig -a | grep -F 'Link encap:Ethernet' | cut -f1 -d' ' | tr '\n' ' '`"
for INTERFACE in $INTERFACES #exs: wlan0 eth0
do
 
 #160909 actual bus may differ from that in /etc/networkmodules...
 IF_BUS=''
 IF_INFO=''
 DRVR_PATH="`readlink /sys/class/net/$INTERFACE/device/driver`"
 IF_DRIVER="`echo -n "$DRVR_PATH" | rev | cut -f1 -d'/' | rev`" #ex: ath5k
 REAL_BUS="`echo -n "$DRVR_PATH" | grep -o '/bus/[a-z]*/drivers/' | cut -f 3 -d '/'`" #ex: sdio
 CUT_DRVR="`basename $IF_DRIVER _${REAL_BUS}`" #ex: brcmfmac_sdio becomes brcmfmac
 dPATTERN="^${IF_DRIVER} "
 WHATWEWANT="`grep "$dPATTERN" /etc/networkmodules | tr '|' '_' | tr '"' '|'`" #'geany
 if [ "$WHATWEWANT" ];then
  #IF_BUS="`echo -n "$WHATWEWANT" | cut -f 2 -d '|' | cut -f 1 -d ':'`" #ex: usb
  IF_INFO="`echo -n "$WHATWEWANT" | cut -f 2 -d '|' | tr -s ' ' | cut -f 2-29 -d ' '`" #ex: Ralink RT73 USB Wireless LAN driver
 else
  dPATTERN="^${CUT_DRVR} "
  WHATWEWANT="`grep "$dPATTERN" /etc/networkmodules | tr '|' '_' | tr '"' '|'`" #'geany
  if [ "$WHATWEWANT" ];then
   IF_INFO="`echo -n "$WHATWEWANT" | cut -f 2 -d '|' | tr -s ' ' | cut -f 2-29 -d ' '`" #ex: Ralink RT73 USB Wireless LAN driver
  fi
 fi
 IF_BUS="$REAL_BUS"

 [ "$IF_BUS" = "" ] && IF_BUS="x"
 [ "$IF_INFO" = "" ] && IF_INFO="x"
 if [ "$IF_DRIVER" == "ndiswrapper" ];then
  WINDRVR="`ndiswrapper -l | grep '^[a-zA-Z0-9]' | cut -f 1 -d ' '`"
  IF_INFO="MS Windows driver '${WINDRVR}'"
  FINDTYPE="`readlink /sys/class/net/$INTERFACE/device/driver`"
  if [ "$FINDTYPE" ];then
   case $FINDTYPE in
    */bus/usb*) IF_BUS="usb" ;;
    */bus/pci*) IF_BUS="pci" ;;
    */bus/sdio*) IF_BUS="sdio" ;; #160922
   esac
  fi
 fi

  #want to manipulate the info string for display purposes...
  CNTLINE=0;FINALINFO=""
  for ONEWORD in $IF_INFO
  do
   CNTWORD=`echo "$ONEWORD" | wc -c`
   CNTLINE=`expr $CNTLINE + $CNTWORD`
   [ $CNTLINE -gt $BIGGESTCNT ] && BIGGESTCNT=$CNTLINE #use for window width.
   [ $CNTLINE -gt 60 ] && break
   FINALINFO="${FINALINFO}${ONEWORD} " #ensures whole words only in string.
  done
  IF_INFO="`echo -n "$FINALINFO"  | tr '[&|"<>]' ' ' | tr -s ' '`" #'geany. filter out chars that mess up xml.
 
 #160922 precaution, IF_DRIVER should match a kernel module name...
 if ! modinfo $IF_DRIVER > /dev/null 2>&1;then IF_DRIVER="$CUT_DRVR"; fi
 
 IF_INTTYPE='Wired'
 ePATTERN="${INTERFACE}:"
 [ "`grep "$ePATTERN" /proc/net/wireless`" != "" ] && IF_INTTYPE='Wireless'
 [ "$IF_DRIVER" = "prism2_usb" ] && IF_INTTYPE='Wireless'
 [ -d /sys/class/net/${INTERFACE}/wireless ] && IF_INTTYPE='Wireless'
 #accumulate the results into columns...
 ALL_IF_INTERFACE="${ALL_IF_INTERFACE}|${INTERFACE}"
 ALL_IF_INTTYPE="${ALL_IF_INTTYPE}|${IF_INTTYPE}"
 ALL_IF_DRIVER="${ALL_IF_DRIVER}|${IF_DRIVER}"
 ALL_IF_BUS="${ALL_IF_BUS}|${IF_BUS}"
 ALL_IF_INFO="${ALL_IF_INFO}|${IF_INFO}"
 INTERFACEBUTTONS="${INTERFACEBUTTONS} 
  <button><label>${INTERFACE}</label><action type=\"exit\">Interface_${INTERFACE}</action></button>"
 #save all data about each interface on one line...
 #ex: wlan1|Wireless|ath5k|pci|Support for 5xxx series of Atheros 802.11 wireless LAN cards
 echo "${INTERFACE}|${IF_INTTYPE}|${IF_DRIVER}|${IF_BUS}|${IF_INFO}" >> /tmp/sns_interfaces
done
ALL_IF_INTERFACE="`echo -n "$ALL_IF_INTERFACE" | sed -e 's%^|%%' | tr '|' '\n'`"
ALL_IF_INTTYPE="`echo -n "$ALL_IF_INTTYPE" | sed -e 's%^|%%' | tr '|' '\n'`"
ALL_IF_DRIVER="`echo -n "$ALL_IF_DRIVER" | sed -e 's%^|%%' | tr '|' '\n'`"
ALL_IF_BUS="`echo -n "$ALL_IF_BUS" | sed -e 's%^|%%' | tr '|' '\n'`"
ALL_IF_INFO="`echo -n "$ALL_IF_INFO" | sed -e 's%^|%%' | tr '|' '\n'`"

INTERFACEDESCR="    <hbox spacing=\"10\">
      <text use-markup=\"true\"><label>\"<b>$(gettext 'Interface')</b>
$ALL_IF_INTERFACE\"</label></text>
      <text use-markup=\"true\"><label>\"<b>$(gettext 'Type')</b>
$ALL_IF_INTTYPE\"</label></text>
      <text use-markup=\"true\"><label>\"<b>$(gettext 'Driver')</b>
$ALL_IF_DRIVER\"</label></text>
      <text use-markup=\"true\"><label>\"<b>$(gettext 'Bus')</b>
$ALL_IF_BUS\"</label></text>
      <text use-markup=\"true\"><label>\"<b>$(gettext 'Description')</b>
$ALL_IF_INFO\"</label></text>
    </hbox>"

#test if connected to internet...
FLAGINTERNETSTATUS='no'
WORKINGIF=''
if [ "`pidof dhcpcd`" != "" ];then
 if [ "`grep -v '^#' /etc/resolv.conf`" != "" ];then
  PSALL="`ps`"
  PSDHCPCD="`echo "$PSALL" | grep 'dhcpcd'`"
  for ONEIF in `ifconfig | grep '^[a-z]' | cut -f 1 -d ' ' | grep -v '^lo' | tr '\n' ' '`
  do
   if [ "`echo "$PSDHCPCD" | grep "$ONEIF"`" != "" ];then
    WORKINGIF="${WORKINGIF}${ONEIF} "
    FLAGINTERNETSTATUS='yes'
   fi
  done
 fi
fi
if [ "$FLAGINTERNETSTATUS" == "yes" ];then
 WORKINGIF="`echo -n "$WORKINGIF" | sed -e 's% $%%'`"
 MSGWIF="interface '${WORKINGIF}'"
 [ `echo -n "$WORKINGIF" | wc -w` -gt 1 ] && MSGWIF="interfaces '${WORKINGIF}'"
 MSGSTATUS="<text use-markup=\"true\"><label>\"<b>$(gettext 'STATUS: Currently there is a working Internet connection, on') ${MSGWIF}</b>\"</label></text>"
else
 MSGSTATUS="<text use-markup=\"true\"><label>\"<b>$(gettext 'STATUS: Currently there is no Internet connection')</b>\"</label></text>"
fi

CLICKMSG="<text><label>$(gettext 'Puppy has identified these network interfaces on your computer. Click a button to configure the interface for use:')</label></text>"
#100313 add a button for loading a Windows driver...
#151101 check if kernel ndiswrapper module exists...
modinfo ndiswrapper > /dev/null 2>&1
if [ $? -eq 0 ];then
 if [ "`echo "$ALL_IF_DRIVER" | grep 'ndiswrapper'`" == "" ];then
  CLICKMSG="<text><label>`gettext \"Puppy has identified these network interfaces on your computer. Click a button to configure the interface for use, or click 'Windows' button if you want to install and use a MS Windows driver:\"`</label></text>"
  INTERFACEBUTTONS="${INTERFACEBUTTONS} 
   <button><label>Windows</label><action type=\"exit\">Interface_Windows</action></button>"
 fi
fi

#170824 new CRD button (code from quicksetup)...
CRDBUTTON=""
if [ -s /etc/iso3166-1-alpha2 ];then #precaution
 DEFAULT_2CH='00'
 [ -f /etc/modprobe.d/crdw.conf ] && DEFAULT_2CH="$(cat /etc/modprobe.d/crdw.conf | grep '^options cfg80211' | cut -f 2 -d '=')" #created by quicksetup
 [ ! "$DEFAULT_2CH" ] && DEFAULT_2CH='00'
 DEFAULT_CRDW="$(grep "^${DEFAULT_2CH} " /etc/iso3166-1-alpha2)" #ex: AU Australia
 [ ! "$DEFAULT_CRDW" ] && DEFAULT_CRDW='00 UNSET'
 DEFAULT_CRDW_ITEM="<item>${DEFAULT_CRDW}</item>"
 if [ "$DEFAULT_2CH" == "00" ];then #161231
  ITEMS="$(sed -e 's%^%<item>%' -e 's%$%</item>%' /etc/iso3166-1-alpha2)"
 else
  ITEMS="<item>00 UNSET</item>$(sed -e 's%^%<item>%' -e 's%$%</item>%' /etc/iso3166-1-alpha2)"
 fi
 TT_crdw="$(gettext 'Choose country for WiFi channels')"
 T_crdw="$(gettext 'CRD:')"
 HH_crdw="$(gettext 'Help: CRD wireless')"
 H_crdw="$(gettext "A wireless network in home or office will broadcast on a channel. These are frequencies, numbered 1 to 14. Some countries only support a subset of these frequencies, and it is possible that a network may use a channel that the Linux kernel thinks is invalid for the country, hence will ignore it.
    
If a channel is ignored, using a network manager, such as <b>SNS</b> (Simple Network Setup), will not find that network.
    
<span color='red'>Recommend, leave the setting at <b>00</b> (unset), unless you encounter the problem of being unable to see a wireless network. Setting it may cause a longer time to establish the wifi connection. Also, currently only SNS properly handles settings other than 00.</span>
    
<b>Technical notes</b>
A list of country codes is in /etc/iso3166-1-alpha2, and /etc/modprobe.d/crdw.conf has the currently selected country code. If the setting is changed from UNSET, file/etc/modprobe.d/crdw.conf will be created, which sets country code when the cfg80211 kernel module loads, which also informs the kernel (verifiable by 'iw reg get').")"
 export DLG_HELP_CRDW="<window resizable=\"false\" title=\"${HH_crdw}\" icon-name=\"${HELPICON}\" window_position=\"1\"><vbox><text use-markup=\"true\"><label>\"${H_crdw}\"</label><variable>DLG_HELP_CRDW</variable></text><hbox><button><label>${M_close}</label><action type=\"closewindow\">DLG_HELP_CRDW</action></button></hbox></vbox></window>"
 CRDBUTTON="<text space-expand=\"false\" space-fill=\"false\"><label>${T_crdw}</label></text>
 <combobox tooltip-text=\"${TT_crdw}\" width-request=\"143\" space-expand=\"false\" space-fill=\"false\">
 ${DEFAULT_CRDW_ITEM}
 ${ITEMS}
 <variable>COMBO_CRDW</variable></combobox>
 <button space-expand=\"false\" space-fill=\"false\"><input file>/usr/local/lib/X11/mini-icons/mini-question.xpm</input><action type=\"launch\">DLG_HELP_CRDW</action></button>
 <text space-expand=\"true\" space-fill=\"true\"><label>\" \"</label></text>
"
fi


#   <text><label>Find out stuff about what is currently working (if anything)</label></text>

#120107 new 'Profile' frame...
PROFILE_XML=""
echo "<b>$(gettext 'Interface')</b>" >/tmp/sns_I_P;  echo "<b>$(gettext 'Type')</b>" >/tmp/sns_T_P; echo "<b>$(gettext 'Driver')</b>" >/tmp/sns_D_P; echo "<b>$(gettext 'Bus')</b>" >/tmp/sns_B_P; echo "<b>$(gettext 'Hardware')</b>" >/tmp/sns_M_P; echo "" >/tmp/sns_S_P; echo "" >/tmp/sns_DEL_BTN; echo "" >/tmp/sns_CNT_P; echo "<b>$(gettext 'Security')</b>" >/tmp/sns_SEC_P
if [ -s /etc/simple_network_setup/connections ];then
 CNT=0
 [ "grep '|Wireless|' /etc/simple_network_setup/connections" != "" ] && echo "<b>$(gettext 'Network')</b>" >/tmp/sns_S_P
 cat /etc/simple_network_setup/connections |
 while read ONECONNECTION
 do
  CNT=$(($CNT + 1))
  echo "<b>$CNT</b>" >> /tmp/sns_CNT_P
  INTERFACE_P="`echo -n "$ONECONNECTION" | cut -f 1 -d '|'`"
  echo "$INTERFACE_P" >> /tmp/sns_I_P
  TYPE_P="`echo -n "$ONECONNECTION" | cut -f 2 -d '|'`"
  echo "$TYPE_P" >> /tmp/sns_T_P
  DRIVER_P="`echo -n "$ONECONNECTION" | cut -f 3 -d '|'`"
  echo "$DRIVER_P" >> /tmp/sns_D_P
  BUS_P="`echo -n "$ONECONNECTION" | cut -f 4 -d '|'`"
  echo "$BUS_P" >> /tmp/sns_B_P
  MAC_P="`echo -n "$ONECONNECTION" | cut -f 6 -d '|'`"
  echo "$MAC_P" >> /tmp/sns_M_P
  if [ "$TYPE_P" = "Wireless" ];then
   SSID_P="`echo -n "$ONECONNECTION" | cut -f 12 -d '|'`"
   echo "$SSID_P" >> /tmp/sns_S_P
   SEC_P="`echo -n "$ONECONNECTION" | cut -f 14 -d '|'`"
   [ "$SEC_P" = "" ] && SEC_P="none"
   echo "$SEC_P" >> /tmp/sns_SEC_P
  else
   echo "" >> /tmp/sns_S_P
   echo "" >> /tmp/sns_SEC_P
  fi
  if [ $CNT -gt 12 ];then
   echo "<i>more...</i>"  >> /tmp/sns_I_P
   break
  fi
  #170522 fix delete buttons... 170706 fix if ssid or password has ' or " chars...
  xCONNECTION="$(echo -n "$ONECONNECTION" | cut -f 1-6 -d '|' | tr '"' '.' | tr "'" '.')"
  echo "<button><label>${CNT}</label><action>grep -v '${xCONNECTION}' /etc/simple_network_setup/connections > /tmp/sns_action1</action><action>mv -f /tmp/sns_action1 /etc/simple_network_setup/connections</action><action type=\"exit\">EXITRESTART></action></button>" >> /tmp/sns_DEL_BTN
  #cp -f /tmp/sns_DEL_BTN /tmp/sns_DEL_BTN-TEST #170522 for debugging.
 done
 if [ "$FLAGINTERNETSTATUS" = "yes" ];then
  CONNECTBTN_XML="<button><label>$(gettext 'DISCONNECT NOW')</label><action>/usr/sbin/networkdisconnect</action><action type=\"exit\">EXITNOW</action></button>"
 else
  CONNECTBTN_XML="<button><label>$(gettext 'CONNECT NOW')</label><action>/usr/sbin/networkdisconnect</action><action>/usr/local/simple_network_setup/rc.network start & </action><action>yaf-splash -timeout 2 -bg orange -close never -fontsize large -text \"$(gettext 'Please wait...')\"</action><action type=\"exit\">EXITNOW</action></button>"
 fi
 PROFILE_XML="<frame $(gettext 'Profiles')>
 <text><label>$(gettext 'Connection profiles have previously been created with SNS. These are:')</label></text>
 <hbox spacing=\"10\"><text use-markup=\"true\"><label>\"`cat /tmp/sns_CNT_P`\"</label></text><text use-markup=\"true\"><label>\"`cat /tmp/sns_I_P`\"</label></text><text use-markup=\"true\"><label>\"`cat /tmp/sns_T_P`\"</label></text><text use-markup=\"true\"><label>\"`cat /tmp/sns_D_P`\"</label></text><text use-markup=\"true\"><label>\"`cat /tmp/sns_B_P`\"</label></text><text use-markup=\"true\"><label>\"`cat /tmp/sns_M_P`\"</label></text><text use-markup=\"true\"><label>\"`cat /tmp/sns_S_P`\"</label></text><text use-markup=\"true\"><label>\"`cat /tmp/sns_SEC_P`\"</label></text></hbox>
 <hbox><text><label>$(gettext 'Delete:')</label></text>`cat /tmp/sns_DEL_BTN`
   <text><label>\"          \"</label></text>
   ${CONNECTBTN_XML}
   <hbox><button><input file>/usr/local/lib/X11/mini-icons/mini-question.xpm</input><action>/usr/local/simple_network_setup/help_profiles & </action></button></hbox>
 </hbox>
</frame>"
fi

#bring up the main window...
export WIN1_DLG="<window title=\"$(gettext 'Simple Network Setup')\" icon-name=\"gtk-network\" resizable=\"false\">
 <vbox>
 <text use-markup=\"true\"><label>\"<b>$(gettext "Welcome to Barry's Simple Network Setup!")</b>\"</label></text>
 <frame $(gettext 'Current status')>
   ${MSGSTATUS}
   <hbox>
     <text><label>$(gettext 'Detailed network interface Information:')</label></text>
     <button><input file>/usr/local/lib/X11/mini-icons/info16.xpm</input><action>ipinfo & </action></button>
   </hbox>
 </frame>
 ${PROFILE_XML}
 <frame $(gettext 'Interfaces')>
   ${CLICKMSG}
   ${INTERFACEDESCR}
   <hbox>${CRDBUTTON}${INTERFACEBUTTONS}</hbox>
 </frame>
 </vbox>
</window>"

RETSTRING="`gtkdialog --program=WIN1_DLG --center`" ###main window###

echo "$RETSTRING"
EXIT="`echo "$RETSTRING" | grep '^EXIT' | cut -f2 -d'"'`" #'geany
[ "`echo "$EXIT" | grep 'EXITRESTART'`" != "" ] && exec sns ###restarting sns###
[ "`echo "$EXIT" | grep 'Interface'`" = "" ] && exit

INTERFACE="`echo -n "$EXIT" | cut -f2 -d '_'`" #ex: wlan1

#170824
COMBO_CRDW="$(echo "$RETSTRING" | grep '^COMBO_CRDW=' | cut -f 2 -d '"')"
if [ "$DEFAULT_CRDW" != "$COMBO_CRDW" ];then
 NEW_CRDW="$(echo -n "$COMBO_CRDW" | cut -f 1 -d ' ')" #ex: AU
 echo "options cfg80211 ieee80211_regdom=${NEW_CRDW}" > /etc/modprobe.d/crdw.conf #set at the next bootup.
 #...at bootup, after module cfg80211 loads, can confirm setting by running 'iw reg get'
 #160926 had taken this out, but seems still need it on my laptop. may need to expand this script,
 #  with a loop, keep plugging away until the setting gets forced. but for now, just do it once...
 echo "#!/bin/ash
 iw reg set ${NEW_CRDW}" > /etc/init.d/z-wifi-puppy
 chmod 755 /etc/init.d/z-wifi-puppy
 iw reg set ${NEW_CRDW} #set now.
 sleep 0.5
fi

if [ "$INTERFACE" == "Windows" ];then #100313
 if [ -d /etc/ndiswrapper ];then
  if [ "`ls /etc/ndiswrapper/*/*.inf 2>/dev/null`" != "" ];then
   modprobe ndiswrapper
   sleep 1
   exec sns
  fi
 fi
 export NDISWRAPPER_DLG="<window title=\"$(gettext 'SNS: Install MS Windows driver')\" icon-name=\"gtk-network\">
 <vbox>
  <pixmap><input file>/usr/local/lib/X11/mini-icons/mini.win95.xpm</input></pixmap>
  <text><label>\"`gettext \"Select the '.inf' file of the required MS Windows driver. If on a CD, you will have to mount it, then navigate to where the '.inf' file is. Note, choose a Windows XP driver if available...\"`\"</label></text>
  <text><label>\"  \"</label></text>
  <chooser>
    <height>300</height><width>550</width>
    <variable>INF_FILE_NAME</variable>
  </chooser>
  <hbox>
    <button ok></button>
    <button cancel></button>
  </hbox>
 </vbox>
 </window>"
 RETSTRND="`gtkdialog --program=NDISWRAPPER_DLG`"
 if [ "`echo "$RETSTRND" | grep '^EXIT' | grep 'OK'`" != "" ];then
  INFFILE="`echo "$RETSTRND" | grep '^INF_FILE_NAME' | cut -f 2 -d '"'`" #'geany
  case "$INFFILE" in
   *.[iI][nN][fF]) 
    FLAGND=""
    ndiswrapper -i "$INFFILE" #installs driver at /etc/ndiswrapper.
    if [ $? -eq 0 ];then
     ndiswrapper -l #tests the driver
     if [ $? -eq 0 ];then
      modprobe ndiswrapper
      [ $? -eq 0 ] && FLAGND="ok"
      [ "$FLAGND" != "ok" ] && rmmod ndiswrapper 2>/dev/null
     fi
    fi
    [ "$FLAGND" != "ok" ] && rm -rf /etc/ndiswrapper
    [ "$FLAGND" != "ok" ] && pupmessage -center -bg red "$(gettext 'ERROR: Windows driver does not seem to work, it has been uninstalled')"
    [ "$FLAGND" == "ok" ] && sleep 1
   ;;
   *) 
    pupmessage -center -bg red "`eval_gettext \"ERROR, \\\${INFFILE} is not a .inf file\"`"
   ;;
  esac
 fi
 exec sns
fi

ifPATTERN='^'"$INTERFACE"' '
if [ "`ifconfig | grep "$ifPATTERN"`" != "" ];then
 #xmessage -center -bg orange -buttons "" "Please wait, bringing down '$INTERFACE'..." &
 yaf-splash -bg orange -placement center -text "$(gettext 'Please wait, bringing down') '$INTERFACE'..." &
 PIDX1=$!
 ifconfig $INTERFACE down
 [ "`iwconfig $INTERFACE | grep "$INTERFACE" | grep "ESSID"`" != "" ] && iwconfig $INTERFACE essid off
 iwconfig $INTERFACE key off #100320 think need this for when I'm experimenting with different wep/wpa/open settings on the same interface.
 #killall dhcpcd
 dhcpcd --release $INTERFACE 2>/dev/null
 ip route flush dev $INTERFACE #100703
 sleep 1
 kill $PIDX1
fi

fPATTERN='^'"${INTERFACE}"'|'
IFDATA="`grep "$fPATTERN" /tmp/sns_interfaces`"
IF_INTTYPE="`echo "$IFDATA" | cut -f2 -d'|'`" #ex: Wireless
IF_DRIVER="`echo "$IFDATA" | cut -f3 -d'|'`" #ex: ath5k
IF_BUS="`echo "$IFDATA" | cut -f4 -d'|'`" #ex: pci
IF_INFO="`echo "$IFDATA" | cut -f5 -d'|'`"
MACADDRESS="`ifconfig $INTERFACE | grep -o 'HWaddr .*' | cut -f 2 -d ' '`"

############WIRELESS SETUP###############
if [ "$IF_INTTYPE" == "Wireless" ];then
 #scan for networks...
 #140201 peebee reported need this... 140217...
 WIF="$(echo -n "$INTERFACE" | grep 'wlan' | sed -e 's%[0-9]$%%')" #convert wlan0 to wlan
 [ "$WIF" ] && [ "`rfkill list ${WIF} | grep 'Soft blocked: yes'`" != "" ] && rfkill unblock $WIF
 FLAGERR=
 rm -f /tmp/sns_scan_radiobuttons
 rm -f /tmp/sns_scan_rawoneline
 rm -f /tmp/sns_scan_oneline
 #xmessage -center -bg orange -buttons "" "Please wait, scanning for wireless networks..." &
 yaf-splash -placement center -bg orange -text "$(gettext 'Please wait, scanning for wireless networks...')" &
 PIDXMSG=$!
 echo "Information about this interface:
 Interface: $INTERFACE  Driver: $IF_DRIVER  Bus: $IF_BUS  MacAddress: $MACADDRESS
 Description: $IF_INFO
 " > /tmp/sns_wireless_log
 [ "`iwconfig $INTERFACE | grep "$INTERFACE" | grep "ESSID"`" != "" ] && iwconfig $INTERFACE essid off
 echo "STEP1a: ifconfig $INTERFACE up" >> /tmp/sns_wireless_log
 ifconfig $INTERFACE up >> /tmp/sns_wireless_log 2>&1
 if [ $? -ne 0 ];then
  FLAGERR=1
 else
  sleep 6 #100513 increase from 1. 151004 increase from 2. 151008 see also below. 160909 increase from 4
  echo "STEP1b: iwlist $INTERFACE scan" >> /tmp/sns_wireless_log
  SCANRESULT="`iwlist $INTERFACE scan`" ###SCANNING### 110203
  #if [ "`echo "$SCANRESULT" | grep 'Scan completed'`" = "" ];then #100513 110203
  # sleep 2
  # SCANRESULT="`iwlist $INTERFACE scan`" ###SCANNING### 110203
  #fi
  echo "$SCANRESULT" >> /tmp/sns_wireless_log
  echo "STEP1c: ifconfig $INTERFACE down" >> /tmp/sns_wireless_log
  ifconfig $INTERFACE down #100313
  #convert each found network into a single line... 110203
  SRLINES="`echo "$SCANRESULT" | grep -v 'Scan completed' | tr '|' ' ' | tr '\n' '|' | sed -e 's%       Cell %\n%g' | tr -s ' '`"
  echo "$SRLINES" |
  while read ONELINE
  do
   [ "$ONELINE" = "" ] && continue
   [ "$ONELINE" = " " ] && continue
   [ "`echo -n "$ONELINE" | grep 'No scan results'`" != "" ] && continue #101029
   [ "`echo -n "$ONELINE" | grep ' ESSID:'`" = "" ] && continue #101029
   CELL_NUMBER="`echo -n "$ONELINE" | cut -f1 -d' '`"
   CELL_ADDRESS="`echo -n "$ONELINE" | grep -o ' Address: .*' | cut -f 3 -d ' ' | cut -f1 -d '|'`"
   CELL_CHANNEL="`echo -n "$ONELINE" | grep -o ' Channel:.*' | cut -f2 -d':' | cut -f1 -d'|'`"
   [ "$CELL_CHANNEL" == "" ] && CELL_CHANNEL="`echo -n "$ONELINE" | grep -o ' (Channel .*' | cut -f 3 -d ' ' | cut -f 1 -d')'`"
   CELL_QUALITY="`echo -n "$ONELINE" | grep -o ' Quality[:=].*' | cut -f 2 -d ' ' | cut -f 2 -d '=' | cut -f 2 -d ':'`"
   CELL_ESSID="`echo -n "$ONELINE" | grep -o ' ESSID:.*' | cut -f 2 -d '"'`" #'geany
   CELL_ENCRYPTIONKEY="`echo -n "$ONELINE" | grep -o 'Encryption key:.*' | cut -f 2 -d ':' | cut -f1 -d '|'`" #ex: off
   CELLMSG="Name: $CELL_ESSID  Encryption: $CELL_ENCRYPTIONKEY  Strength: $CELL_QUALITY"
   echo "<radiobutton><label>${CELLMSG}</label><variable>RADIO_${CELL_NUMBER}</variable></radiobutton>" >> /tmp/sns_scan_radiobuttons
   echo "$ONELINE" >> /tmp/sns_scan_rawoneline
   echo "${CELL_NUMBER}|${CELL_ADDRESS}|${CELL_CHANNEL}|${CELL_QUALITY}|${CELL_ENCRYPTIONKEY}|${CELL_ESSID}" >> /tmp/sns_scan_oneline
  done
 
  #my wpa_supplicant only supports: wext hostap atmel wired ralink roboswitch
  case $IF_DRIVER in
   hostap*)   WPA_DRIVER="hostap" ;;
   rt61|rt73) WPA_DRIVER="ralink" ;;
   *)         WPA_DRIVER="wext" ;;
  esac
 
  if [ ! -f /tmp/sns_scan_radiobuttons ];then
   FRAME1="<frame $(gettext 'Wireless networks')><text><label>\" \"</label></text><text><label>$(gettext 'No wireless networks found')</label></text></frame><text><label>\" \"</label></text>"
   FRAME2=""
   WIN2MSG1=""
   WIN2BUT1=""
  else
   WIN2MSG1="<text><label>`gettext \"Choose which network you want to use, type of encryption, then click 'CONNECT' button:\"`</label></text>"
   RADIOBUTTONS="`cat /tmp/sns_scan_radiobuttons | sort -t: -k4 -n -r`" #170521 sort in order of signal strength.
   if [ `cat /tmp/sns_scan_radiobuttons | wc -l` -lt 12 ];then #130221
    FRAME1="<frame $(gettext 'Wireless networks')><text><label>\" \"</label></text>${RADIOBUTTONS}<text><label>\" \"</label></text></frame>"
   else
    #130221 vertical scrollbar...
    FRAME1="<frame $(gettext 'Wireless networks')><vbox scrollable=\"true\"  height=\"250\" width-request=\"450\" width=\"450\">
     <text><label>\" \"</label></text>${RADIOBUTTONS}<text><label>\" \"</label></text>
    </vbox></frame>"
   fi
   FRAME2="<frame $(gettext 'Encryption')>
   <hbox>
    <vbox>
     <radiobutton><label>$(gettext 'none')</label><variable>BUTSEC_NONE</variable></radiobutton>
     <radiobutton><label>WEP</label><variable>BUTSEC_WEP</variable></radiobutton>
     <radiobutton><label>WPA</label><variable>BUTSEC_WPAPSK</variable></radiobutton>
    </vbox>
    <text><label>\"    \"</label></text>
    <vbox>
     <hbox><text><label>$(gettext 'Key:')</label></text><entry><variable>BOX_KEY</variable></entry></hbox>
     <hbox><button><label>$(gettext 'HELP')</label><action>/usr/local/simple_network_setup/help_security & </action></button></hbox>
    </vbox>
   </hbox>
   </frame>"
   WIN2BUT1="<button><label>$(gettext 'CONNECT')</label><action type=\"exit\">BUT_CONNECT</action></button>"
  fi

  kill $PIDXMSG ; PIDXMSG=""

  export WIN2_DLG="<window title=\"$(gettext 'Simple Network Setup')\" icon-name=\"gtk-network\">
  <vbox>
   ${FRAME1}
   ${FRAME2}
   ${WIN2MSG1}
   <hbox>
    ${WIN2BUT1}
    <button><label>$(gettext 'GO BACK TO MAIN WINDOW')</label><action type=\"exit\">BUT_GOBACK</action></button>
   </hbox>
  </vbox>
  </window>"
  RETSTRING="`gtkdialog --program=WIN2_DLG --center`" 
  [ "`echo "$RETSTRING" | grep '^EXIT' | grep 'BUT_GOBACK'`" != "" ] && exec sns
  [ "`echo "$RETSTRING" | grep '^EXIT' | grep 'BUT_CONNECT'`" == "" ] && exit

  SEC_MGMT=""; WPA_ENC=""
  SEC_KEY="`echo "$RETSTRING" | grep '^BOX_KEY' | cut -f 2 -d '"' | tr -d '-'`" #'geany
  BUTSEC="`echo "$RETSTRING" | grep '^BUTSEC_' | grep 'true' | cut -f 1 -d '=' | cut -f 2 -d '_'`"
  case $BUTSEC in
   WEP)        SEC_MGMT="WEP"; WPA_ENC=""  ;;
   WPAPSK)     SEC_MGMT="WPA-PSK"; WPA_ENC="" ;;
   WPAPSKTKIP) SEC_MGMT="WPA-PSK"; WPA_ENC="TKIP" ;;
   WPAPSKAES)  SEC_MGMT="WPA-PSK"; WPA_ENC="AES" ;;
   WPA2PSKAES) SEC_MGMT="WPA2-PSK"; WPA_ENC="AES"  ;;
   *)          SEC_KEY="" ;; #no encryption.
  esac 
 
  CELL_NUMBER="`echo "$RETSTRING" | grep '^RADIO' | grep 'true' | cut -f1 -d'=' | cut -f2 -d'_'`" #ex: 01
  cnPATTERN='^'"$CELL_NUMBER"'|'
  CELLDATA="`grep "$cnPATTERN" /tmp/sns_scan_oneline`"
  CELL_ADDRESS="`echo -n "$CELLDATA" | cut -f2 -d'|'`"
  CELL_CHANNEL="`echo -n "$CELLDATA" | cut -f3 -d'|'`"
  CELL_QUALITY="`echo -n "$CELLDATA" | cut -f4 -d'|'`"
  CELL_ENCRYPTIONKEY="`echo -n "$CELLDATA" | cut -f5 -d'|'`"
  CELL_ESSID="`echo -n "$CELLDATA" | cut -f6 -d'|'`"
 
  if [ "$CELL_ENCRYPTIONKEY" == "on" ];then
   [ "$SEC_KEY" == "" ] && FLAGERR=2
   [ "$SEC_MGMT" == "" ] && FLAGERR=3
  fi
  if [ ! $FLAGERR ];then
 
   #xmessage -center -bg orange -buttons "" "Please wait, attempting to connect to '${CELL_ESSID}'..." &
   yaf-splash -placement center -bg orange -text "$(gettext 'Please wait, attempting to connect to') '${CELL_ESSID}'..." &
   PIDX=$!
   echo "STEP2: iwconfig $INTERFACE mode managed" >> /tmp/sns_wireless_log
   iwconfig $INTERFACE mode managed  >> /tmp/sns_wireless_log 2>&1
   echo "STEP3: iwconfig $INTERFACE channel $CELL_CHANNEL" >> /tmp/sns_wireless_log
   iwconfig $INTERFACE channel $CELL_CHANNEL  >> /tmp/sns_wireless_log 2>&1
   echo "STEP4: iwconfig $INTERFACE essid \"$CELL_ESSID\"" >> /tmp/sns_wireless_log
   iwconfig $INTERFACE essid "$CELL_ESSID"  >> /tmp/sns_wireless_log 2>&1

   #test essid is associated...
   if [ $? -ne 0 ];then
    FLAGERR=4
   else
   
    RUNWPASUPP='no'
    [ -f "/etc/simple_network_setup/wpa_supplicant.conf-${CELL_ESSID}-${MACADDRESS}" ] && rm -f "/etc/simple_network_setup/wpa_supplicant.conf-${CELL_ESSID}-${MACADDRESS}"
    FIXUP='1 1 2 0'
    [ "$IF_DRIVER" = "ndiswrapper" ] && FIXUP='2 1 0'
    [ "$BUTSEC" = "WEP" ] && FIXUP='restricted open'
    fuCNT=`echo -n "$FIXUP" | wc -w`
    fuCNT=$(($fuCNT + 1)) #100321 bug fix.
    for ONEFIX in $FIXUP ###BIG FOR LOOP###
    do
     FLAGERR= #100323
     fuCNT=$(($fuCNT - 1))
     if [ "$CELL_ENCRYPTIONKEY" == "on" ];then
      case $BUTSEC in
       WEP)
        echo "STEP5: iwconfig $INTERFACE key $ONEFIX $SEC_KEY" >> /tmp/sns_wireless_log
        iwconfig $INTERFACE key $ONEFIX $SEC_KEY
       ;;
       WPAPSK) #very simple, handles all ciphers.
        #it works psk="passphrase" (with quotes), but for security encode psk into hex string...
        hexSEC_KEY=`wpa_passphrase "$CELL_ESSID" $SEC_KEY | grep '[^#]psk=' | cut -f 2 -d '='`
        echo "ctrl_interface=/var/run/wpa_supplicant
ap_scan=${ONEFIX}

network={
 ssid=\"${CELL_ESSID}\"
 key_mgmt=${SEC_MGMT}
 psk=${hexSEC_KEY}
}" > "/etc/simple_network_setup/wpa_supplicant.conf-${CELL_ESSID}-${MACADDRESS}"
        RUNWPASUPP='yes'
        if [ "`pidof wpa_supplicant`" != "" ];then
         wpa_cli terminate
         killall wpa_supplicant
        fi
       ;;
       WPA*)  
        #it works psk="passphrase" (with quotes), but for security encode psk into hex string...
        hexSEC_KEY=`wpa_passphrase "$CELL_ESSID" $SEC_KEY | grep '[^#]psk=' | cut -f 2 -d '='`
        echo "ctrl_interface=/var/run/wpa_supplicant
ap_scan=${ONEFIX}

network={
 ssid=\"${CELL_ESSID}\"
 proto=WPA
 key_mgmt=${SEC_MGMT}
 pairwise=${WPA_ENC}
 group=${WPA_ENC}
 psk=${SEC_KEY}
 wpa_ptk_rekey=600
}" > "/etc/simple_network_setup/wpa_supplicant.conf-${CELL_ESSID}-${MACADDRESS}"
        RUNWPASUPP='yes'
        if [ "`pidof wpa_supplicant`" != "" ];then
         wpa_cli terminate #kills any running wpa_supplicant. no it doesn't, just brings down interface.
         killall wpa_supplicant
        fi
       ;;
      esac
     fi
 
     echo "STEP5a: ifconfig $INTERFACE up" >> /tmp/sns_wireless_log
     ifconfig $INTERFACE up
     sleep 4 #151008 new sleep.
     if [ "$RUNWPASUPP" = "yes" ];then
      echo "STEP5b: wpa_supplicant -B -D${WPA_DRIVER} -i${INTERFACE} -c\"/etc/simple_network_setup/wpa_supplicant.conf-${CELL_ESSID}-${MACADDRESS}\"" >> /tmp/sns_wireless_log
      wpa_supplicant -B -D${WPA_DRIVER} -i${INTERFACE} -c"/etc/simple_network_setup/wpa_supplicant.conf-${CELL_ESSID}-${MACADDRESS}" >> /tmp/sns_wireless_log 2>&1
      wCNT=0
      while [ 1 ];do
       [ "`wpa_cli -i $INTERFACE status | grep '^bssid=[0-9a-f]'`" != "" ] && break
       sleep 1
       wCNT=`expr $wCNT + 1`
       if [ $wCNT -gt 20 ];then
        echo "Running: wpa_cli -i ${INTERFACE} status" >> /tmp/sns_wireless_log
        wpa_cli -i $INTERFACE status >> /tmp/sns_wireless_log 2>&1
        #FLAGERR=5
        #100314 http://wiki.archlinux.org/index.php/WPA_supplicant has following advice...
        #really weird, works for my wg311 ndiswrapper driver. but must have the ap_scan sequence 2 1 0...
        #ignore error, do this instead...
        killall -SIGHUP wpa_supplicant
        iwconfig $INTERFACE essid "$CELL_ESSID"
        break
       fi
      done
     fi
     if [ $FLAGERR ];then
      #if [ "$RUNWPASUPP" == "yes" ];then
       if [ $fuCNT -ne 0 ];then
        kill $PIDX
        case $fuCNT in
         1) BGCOLOR="HotPink" ;;
         2) BGCOLOR="pink" ;;
         *) BGCOLOR="DeepPink" ;;
        esac
        #xmessage -center -bg $BGCOLOR -buttons "" "Please keep waiting, retrying encrypted connection..." &
        yaf-splash -placement center -bg $BGCOLOR -text "$(gettext 'Please keep waiting, retrying encrypted connection...')" &
        PIDX=$!
        continue #try next FIXUP value (see for-loop above). ###BIG FOR LOOP###
       fi
      #fi
      if [ "`pidof wpa_supplicant`" != "" ];then
       wpa_cli terminate
       killall wpa_supplicant
      fi
      [ "`iwconfig $INTERFACE | grep "$INTERFACE" | grep "ESSID"`" != "" ] && iwconfig $INTERFACE essid off
      ifconfig $INTERFACE down
     else
 
      #wait until access point becomes available...
      sCNT=0
      while [ 1 ];do
       TESTAP="`iwconfig ${INTERFACE} | grep -o 'Access Point: .*' | tr -s ' ' | cut -f 3 -d ' ' | sed -e 's%[^:]%%g'`"
       [ "`echo -n "$TESTAP" | grep '::::'`" != "" ] && break
       sleep 1
       sCNT=`expr $sCNT + 1`
       if [ $sCNT -gt 20 ];then
        echo "" >> /tmp/sns_wireless_log #100320
        echo "ERROR, TIMEOUT. Have not got an Access Point." >> /tmp/sns_wireless_log #100320
        echo "Result of 'iwconfig ${INTERFACE}':" >> /tmp/sns_wireless_log #100320
        iwconfig ${INTERFACE} >> /tmp/sns_wireless_log 2>&1 #100320
        echo "" >> /tmp/sns_wireless_log #100320
        FLAGERR=7
        break
       fi
      done
      if [ $FLAGERR ];then
       #if [ "$RUNWPASUPP" == "yes" ];then
        if [ $fuCNT -ne 0 ];then
         kill $PIDX
         case $fuCNT in
          1) BGCOLOR="HotPink" ;;
          2) BGCOLOR="pink" ;;
          *) BGCOLOR="DeepPink" ;;
         esac
         #xmessage -center -bg $BGCOLOR -buttons "" "Please keep waiting, retrying encrypted connection..." &
         yaf-splash -placement center -bg $BGCOLOR -text "$(gettext 'Please keep waiting, retrying encrypted connection...')" &
         PIDX=$!
         continue #try next FIXUP parameter (see for-loop above). ###BIG FOR LOOP###
        fi
       #fi
       [ "`iwconfig $INTERFACE | grep "$INTERFACE" | grep "ESSID"`" != "" ] && iwconfig $INTERFACE essid off
       ifconfig $INTERFACE down
      else
    
       #finally, run dhcpcd...
       [ -f /tmp/sns_interface_success ] && rm -f /tmp/sns_interface_success #170706 precaution.
       MODTIME1="`stat --format=%Y /etc/resolv.conf`"
       for iterDHCPCD in a b #100320
       do
        [ "$iterDHCPCD" = "a" ] && DHCPCDFIX=""
        [ "$iterDHCPCD" = "b" ] && DHCPCDFIX="-I ''" #some dhcp servers require empty Client ID (default is macaddress).
        echo "STEP6${iterDHCPCD}: dhcpcd $DHCPCDFIX $INTERFACE" >> /tmp/sns_wireless_log
        dhcpcd $DHCPCDFIX $(dhcpcd_dropwait_option) $INTERFACE >> /tmp/sns_wireless_log 2>&1 ####DHCP CLIENT#### 121117
        mCNT=0
        while [ 1 ];do
         MODTIME2="`stat --format=%Y /etc/resolv.conf`"
         [ "$MODTIME2" != "$MODTIME1" ] && break 2
         sleep 1
         mCNT=`expr $mCNT + 1`
         if [ $mCNT -gt 20 ];then
          [ "$iterDHCPCD" != "b" ] && dhcpcd --release $INTERFACE
          break
         fi
        done
       done
       [ "$MODTIME2" == "$MODTIME1" ] && FLAGERR=6
       [ "`grep -v '^#' /etc/resolv.conf`" == "" ] && FLAGERR=6
        
       if [ $FLAGERR ];then
        if [ "`pidof wpa_supplicant`" != "" ];then
         wpa_cli terminate
         killall wpa_supplicant
        fi
        [ "`iwconfig $INTERFACE | grep "$INTERFACE" | grep "ESSID"`" != "" ] && iwconfig $INTERFACE essid off
        ifconfig $INTERFACE down
        dhcpcd --release $INTERFACE 2>/dev/null
        ip route flush dev $INTERFACE #100703
       else

        #success!
        echo "$INTERFACE" > /tmp/sns_interface_success #101118
        #100413 have one pc where blinky did not start. try again...
        [ "`which blinky_tray`" ] && [ "`pidof blinky_tray`" = "" ] && blinky_tray &
        essidPATTERN='|'"$CELL_ESSID"'|'
        touch /etc/simple_network_setup/connections
        grep -v "$essidPATTERN" /etc/simple_network_setup/connections > /tmp/sns_temp2
        mv -f /tmp/sns_temp2 /etc/simple_network_setup/connections
        case $SEC_MGMT in
         WEP) ENCODEPROTO="$ONEFIX"; WPA_DRIVER="" ;; #exs: restricted, open
         *) ENCODEPROTO="$WPA_ENC" ;; #exs: AES, TKIP
        esac
        echo "${IFDATA}|${MACADDRESS}|${CELLDATA}|${SEC_KEY}|${SEC_MGMT}|${ENCODEPROTO}|${WPA_DRIVER}|${DHCPCDFIX}|" >> /etc/simple_network_setup/connections
        MSGFIREWALL=""
        CHKFIREWALL=""
        #161022 firewall_ng is in /etc/init.d/rc.firewall when installed...
        FIREWALL_INSTALLED='no'
        [ "`grep '/etc/rc.d/rc.firewall' /etc/rc.d/rc.local`" != "" ] && FIREWALL_INSTALLED='yes' #old Linux Firewall.
        [ -e /etc/init.d/rc.firewall ] && FIREWALL_INSTALLED='yes'
        if [ "$FIREWALL_INSTALLED" != "yes" ];then
         MSGFIREWALL="<text><label>`gettext \"However, there is one item of recommended housekeeping: you really should be running a firewall. Puppy is inherently secure, however a firewall will give you that extra protection while online. Recommend that you tick the 'Start firewall' checkbox (the firewall will install and will automatically run at all future boots)...\"`</label></text>"
         CHKFIREWALL="<checkbox><label>$(gettext 'Start firewall')</label><default>true</default><variable>CHK_FIREWALL</variable></checkbox>"
        fi
        kill $PIDX
        export WIN3_DLG="<window title=\"$(gettext 'SNS: Simple Network Setup')\" icon-name=\"gtk-network\">
        <vbox>
         <pixmap><input file>/usr/local/lib/X11/pixmaps/ok.xpm</input></pixmap>
         <text><label>$(gettext 'Successful connection to wireless network') '${CELL_ESSID}'!</label></text>
         <text><label>$(gettext 'Your Internet should now be working!')</label></text>
         ${MSGFIREWALL}
         ${CHKFIREWALL}
         <text><label>`gettext \"Recommend leave this checkbox ticked, so that Puppy will use SNS to automatically connect to the Internet at bootup. Also clicking the 'connect' icon on the desktop will immediately launch SNS...\"`</label></text>
         <checkbox><label>$(gettext 'Set SNS as default network setup tool')</label><default>true</default><variable>CHK_SNSDEF</variable></checkbox>
         <hbox>
          <button ok></button>
         </hbox>
        </vbox>
        </window>"
        RETSTR3="`gtkdialog --program=WIN3_DLG --center`"
        if [ "`echo "$RETSTR3" | grep '^CHK_SNSDEF' | grep 'true'`" != "" ];then
         echo -e '#!/bin/sh\nexec sns' > /usr/local/bin/defaultconnect
        else
         echo -e '#!/bin/sh\nexec connectwizard' > /usr/local/bin/defaultconnect
        fi
        if [ "`echo "$RETSTR3" | grep '^CHK_FIREWALL' | grep 'true'`" != "" ];then
         if which firewall_ng >/dev/null; then #161106
          firewall_ng
         else
          rxvt -e firewallinstallshell
         fi
        fi
       fi #end test dhcpcd timeout.
      fi #end test access point.
     fi #end test wpa_supplicant timeout.
     break
    done #end for-loop. ###END BIG FOR LOOP###
   fi #end test associate essid.
  fi #end test exist security entries.
 fi #end test ifconfig up

 if [ $FLAGERR ];then
  [ $PIDXMSG ] && kill $PIDXMSG
  [ $PIDX ] && kill $PIDX
  case $SEC_MGMT in
  WPA*) ERR_EXTRA1="$(gettext 'Note: the network card and/or Linux driver might not support WPA2, in which case you will need to set the wireless router to WPA. Or, WPA might not be supported at all, in which case you will have to set the router and network card to use WEP.')" ;;
  *)    ERR_EXTRA1="" ;;
  esac
  case $FLAGERR in
   1)
    ERR_MSG="$(eval_gettext "Failed to activate interface '\${INTERFACE}. Sometimes this is just a temporary problem. Go back to the main window, and you can try again...")"
    ERR_EXTRA1="" 
   ;;
   2) ERR_MSG="$(gettext 'ERROR: you did not specify a Key')" ; ERR_EXTRA1="" ;;
   3) ERR_MSG="$(gettext 'ERROR: you need to choose WEP or WPA security')" ; ERR_EXTRA1="" ;;
   4) ERR_MSG="`eval_gettext \"Failed to associate '\\\${CELL_ESSID}' with ESSID.\"`"; ERR_EXTRA1="" ;;
   7) ERR_MSG="$(gettext 'Failed to obtain Access Point of network.')";  ERR_EXTRA1="" ;;
   5) ERR_MSG="$(gettext 'wpa_supplicant has timed out trying to associate with the network card.')" ;;
   6) ERR_MSG="$(gettext 'DHCP client failed to negotiate with wireless network') '${CELL_ESSID}'" ;;
   *) ERR_MSG="$(gettext 'Failed to connect to wireless network') '${CELL_ESSID}'" ;;
  esac
  export WIN3_DLG="<window title=\"$(gettext 'Simple Network Setup')\" icon-name=\"gtk-network\">
 <vbox>
  <pixmap><input file>/usr/local/lib/X11/pixmaps/error.xpm</input></pixmap>
  <text use-markup=\"true\"><label>\"<b>${ERR_MSG}</b>
${ERR_EXTRA1}\"</label></text>
  <text><label>`gettext \"So, what do you want to do? If you go back to the main window, you could test a different interface or network. Note, sometimes an error 'goes away' if you retry.\"`</label></text>
  <text><label>\"  \"</label></text>
  <hbox>
   <text><label>$(gettext 'View log of attempted connection:')</label></text>
   <button><label>$(gettext 'LOG')</label><action>echo ' ' >> /tmp/sns_wireless_log</action><action>echo '*********************************************************' >> /tmp/sns_wireless_log</action><action>echo 'LAST 10 LINES of /var/log/messages:' >> /tmp/sns_wireless_log</action><action>tail -n 10 /var/log/messages >> /tmp/sns_wireless_log</action><action>defaulttextviewer /tmp/sns_wireless_log & </action></button>
  </hbox>
  <text><label>\"  \"</label></text>
  <hbox>
    <button><label>$(gettext 'GO BACK TO MAIN WINDOW')</label><action type=\"exit\">BUT_GOBACK</action></button>
    <button><label>$(gettext 'QUIT')</label><action type=\"exit\">BUT_QUIT</action></button>
   </hbox>
 </vbox>
</window>"
  RETSTRING="`gtkdialog --program=WIN3_DLG --center`"
  [ "`echo "$RETSTRING" | grep '^EXIT' | grep 'BUT_GOBACK'`" != "" ] && exec sns
 fi

 exit
fi #end test "$IF_INTTYPE" == "Wireless"

############Wired setup###############
if [ "$IF_INTTYPE" == "Wired" ];then
 #xmessage -center -bg orange -buttons "" "Please wait, trying to connect to interface '${INTERFACE}'..." &
 yaf-splash -placement center -bg orange -text "$(gettext 'Please wait, trying to connect to interface') '${INTERFACE}'..." &
 PIDXX=$!
 echo "Information about this interface:
 Interface: $INTERFACE  Driver: $IF_DRIVER  Bus: $IF_BUS  MacAddress: $MACADDRESS
 Description: $IF_INFO
 " > /tmp/sns_wired_log
 
 MODTIME1="1"; MODTIME2="1"
 ifconfig $INTERFACE up >> /tmp/sns_wired_log 2>&1
 [ $? -eq 0 ] && MODTIME2="0"
 if [ "$MODTIME2" == "0" ];then
  if ! ${IFPLUGSTATUS018} "$INTERFACE" | grep -F -q 'link beat detected' ;then #170522
   sleep 2
   if ! ifplugstatus "$INTERFACE" | grep -F -q 'link beat detected' ;then
    sleep 4
    if ! ${IFPLUGSTATUS018} "$INTERFACE" | grep -F -q 'link beat detected' ;then #170522
     sleep 8
     if ! ifplugstatus "$INTERFACE" | grep -F -q 'link beat detected' ;then
      # add ethtool test, just in case it helps at times...
      sleep 16
      if ! ethtool "$INTERFACE" | grep -Fq 'Link detected: yes' ; then
       ifconfig $INTERFACE down
       kill $PIDXX
       export WIN4_DLG="<window title=\"$(gettext 'Simple Network Setup')\" icon-name=\"gtk-network\">
  <vbox>
   <pixmap><input file>/usr/local/lib/X11/pixmaps/error.xpm</input></pixmap>
   <text><label>$(gettext 'There does not seem to be any network connected to') '${INTERFACE}'</label></text>
   <text><label>`gettext \"Is the network cable unplugged? Modem router turned off? If you can fix it, great, otherwise try a different interface. Click 'GO BACK TO MAIN WINDOW' button to try again...\"`</label></text>
   <hbox>
     <button><label>$(gettext 'GO BACK TO MAIN WINDOW')</label><action type=\"exit\">BUT_GOBACK</action></button>
     <button><label>$(gettext 'QUIT')</label><action type=\"exit\">BUT_QUIT</action></button>
    </hbox>
  </vbox>
 </window>"
       RETSTRING="`gtkdialog --program=WIN4_DLG --center`"
       [ "`echo "$RETSTRING" | grep '^EXIT' | grep 'BUT_GOBACK'`" != "" ] && exec sns
       exit
      fi
     fi
    fi
   fi
  fi
  [ -f /tmp/sns_interface_success ] && rm -f /tmp/sns_interface_success #170706 precaution.
  MODTIME1="`stat --format=%Y /etc/resolv.conf`"
  DHCPCDFIX=""
  dhcpcd $INTERFACE >> /tmp/sns_wired_log 2>&1
  #180924 need to wait awhile...
  sleep 0.5 #0.1 #180110
  if ! grep '^nameserver' /etc/resolv.conf >/dev/null; then sleep 0.5; fi
  if ! grep '^nameserver' /etc/resolv.conf >/dev/null; then sleep 0.5; fi
  MODTIME2="`stat --format=%Y /etc/resolv.conf`"
  [ "`grep -v '^#' /etc/resolv.conf`" == "" ] && MODTIME2=$MODTIME1 #fail.
  if [ "$MODTIME2" = "$MODTIME1" ];then #100325 fail, try again.
   DHCPCDFIX="-I ''"
   dhcpcd --release $INTERFACE
   dhcpcd -I '' $INTERFACE >> /tmp/sns_wired_log 2>&1
   MODTIME2="`stat --format=%Y /etc/resolv.conf`"
   [ "`grep -v '^#' /etc/resolv.conf`" == "" ] && MODTIME2=$MODTIME1 #fail.
  fi
 fi
 kill $PIDXX

 if [ "$MODTIME2" != "$MODTIME1" ];then
  export WIN5_DLG="<window title=\"$(gettext 'Simple Network Setup')\" icon-name=\"gtk-network\">
 <vbox>
  <pixmap><input file>/usr/local/lib/X11/pixmaps/ok.xpm</input></pixmap>
  <text><label>$(gettext 'Successful connection to wired network'): '${INTERFACE}'!</label></text>
  <text><label>$(gettext 'Your Internet should now be working!')</label></text>
  <text><label>$(gettext "Recommend leave this checkbox ticked, so that Puppy will use SNS to automatically connect to the Internet at bootup. Also clicking the 'connect' icon on the desktop will immediately launch SNS...")</label></text>
  <checkbox><label>$(gettext 'Set SNS as default network setup tool')</label><default>true</default><variable>CHK_SNSDEF</variable></checkbox>
  <hbox><button ok></button></hbox>
 </vbox>
</window>"
  RETSTR5="`gtkdialog --program=WIN5_DLG --center`"
  if [ "`echo "$RETSTR5" | grep '^CHK_SNSDEF' | grep 'true'`" != "" ];then
   echo -e '#!/bin/sh\nexec sns' > /usr/local/bin/defaultconnect
  else
   echo -e '#!/bin/sh\nexec connectwizard' > /usr/local/bin/defaultconnect
  fi
  MACADDRESS="`ifconfig $INTERFACE | grep -o 'HWaddr .*' | cut -f 2 -d ' '`"
  aPATTERN='|'"$MACADDRESS"'|'
  touch /etc/simple_network_setup/connections
  grep -v "$aPATTERN" /etc/simple_network_setup/connections > /tmp/sns_temp2
  mv -f /tmp/sns_temp2 /etc/simple_network_setup/connections
  echo "${IFDATA}|${MACADDRESS}|${DHCPCDFIX}|" >> /etc/simple_network_setup/connections
  echo "$INTERFACE" > /tmp/sns_interface_success #170522
 else
  ifconfig $INTERFACE down
  dhcpcd --release $INTERFACE 2>/dev/null
  ip route flush dev $INTERFACE #100703
  export WIN6_DLG="<window title=\"$(gettext 'Simple Network Setup')\" icon-name=\"gtk-network\">
 <vbox>
  <pixmap><input file>/usr/local/lib/X11/pixmaps/error.xpm</input></pixmap>
  <text><label>$(gettext 'Failed to connect to wired network') '${INTERFACE}'</label></text>
  <text><label>$(gettext "The network does exist, however failed to negotiate with the DHCP server. Is there a wireless interface? -- maybe try that. Click 'GO BACK TO MAIN WINDOW' button to try again...")</label></text>
  <text><label>\"  \"</label></text>
  <hbox>
   <text><label>$(gettext 'View log of attempted connection:')</label></text>
   <button><label>$(gettext 'LOG')</label><action>defaulttextviewer /tmp/sns_wired_log & </action></button>
  </hbox>
  <text><label>\"  \"</label></text>
  <hbox>
    <button><label>$(gettext 'GO BACK TO MAIN WINDOW')</label><action type=\"exit\">BUT_GOBACK</action></button>
    <button><label>$(gettext 'QUIT')</label><action type=\"exit\">BUT_QUIT</action></button>
   </hbox>
 </vbox>
</window>"
  RETSTRING="`gtkdialog --program=WIN6_DLG --center`"
  [ "`echo "$RETSTRING" | grep '^EXIT' | grep 'BUT_GOBACK'`" != "" ] && exec sns
 fi
 exit
fi

###END###
