#!/bin/bash
# Porteus network setup tool

# Switch to root
if [ `whoami` != "root" ]; then
    echo "Please enter your root password below"
    su - -c "/opt/porteus-scripts/xpns-tool.sh `whoami`" || sleep 1
    exit
fi

# Variables
DIR="/tmp/pns-tool"
TMP="/tmp/pns-tmp"
FILE=$TMP/rc.local
RCLOCAL="$DIR/etc/rc.d/rc.local"
SUPPLICANT="$TMP/wpa_supplicant.conf"
WPASUPPLICANT="$DIR/etc/wpa_supplicant.conf"
INET="$TMP/rc.inet1"
RCINET="$DIR/etc/rc.d/rc.inet1"
TITLE="Porteus Network Setup"
LOG=/tmp/log.txt
DMP=$TMP/dmp
TXT=$TMP/textbox.txt
MSG=$TMP/msg.txt
MENU=$TMP/menufile
MEN=$TMP/men
DATE=`date +%c`


c='\e[36m'
r='\e[31m'
e=`tput sgr0`

# Check if script was run by normal user
if [ "$1" ]; then pth=home/$1; else pth=root; fi

# Catch output from Xdialog
catch() {
ANSW=`cat $DMP`
}

# Check if the cancel button was pressed
chkbut() {
case $? in
   1) cleanup
      exit
      ;;
 255) cleanup
      exit
      ;;
esac
}

# Cleanup your mess
cleanup() {
[ -d $DIR ] && rm -rf $DIR
[ -d $TMP ] && rm -rf $TMP
}

# Generate a simple text box dialog
textbox() {
Xdialog --title "$1" --no-cancel --ok-label Continue --textbox $TXT 0 0
chkbut
}

# An xdialog menu box
# $1 is the menu text
# Echo your menu list to $MEN 
# Call this function and answer is held in $ANSW
menubox() {
#Make a menu from dump file
for a in `cat $MEN`; do
   echo $a $a >> $MENU
done

Xdialog --title "$TITLE" --no-tag --menubox "$1" 0 0 8 `cat $MENU` 2> $DMP
chkbut
ANSW=`cat $DMP`
rm $DMP
rm $MEN
}

# An xdialog input box for typing into
# $1 is the Text for the box
# $2 is the default initial text
# input text is saved in $INPUTANSW
inputbox (){
Xdialog --title "$TITLE" --inputbox "$1" 0 0 "$2" 2> $DMP
chkbut
INPUTANSW=`cat $DMP`
rm $DMP
}

# Generate a yesno answer box
yesno() {
Xdialog --title "$TITLE" --backtitle "$1" --yesno "$2" 0 0
chkbut
}

# Generate a message box
# Just echo your message into $MSG then call this function
messagebox() {
Xdialog --title "$TITLE" --no-cancel --wrap --left --msgbox \
"`cat $MSG`" 0 0
chkbut
rm $MSG
}

# Info box for sending messages
# $1 is the message to be shown - $2 is the time in x/1000 sec
infobox() {
Xdialog --title "$TITLE" --no-buttons --infobox "$1" 0 0 $2
}

# Some device info
get_device_info() {
echo "OUTPUT FROM IFCONFIG" > $TXT
echo "" >> $TXT
ifconfig >> $TXT
echo "" >> $TXT
echo "OUTPUT FROM IWCONFIG" >> $TXT
echo "" >> $TXT
iwconfig >> $TXT
textbox "Some device info" 
rm $TXT
rm $MENU
}

# Create a troubleshooting log
generate_log() {
Xdialog --title "$TITLE" --msgbox "WHAT TO DO WITH THE  LOG\n\n

After pressing OK a log will be generated in your desktop.
You can post the contents of this log on the Porteus forum
with a request for some assistance. \n\n

Press OK to create the log file" 0 0

LOG=/$pth/Desktop/pns-tool.log
touch $LOG
echo "IFCONFIG:" > $LOG
echo "===================" >> $LOG
ifconfig >> $LOG 2>&1
echo "" >> $LOG
echo "IWCONFIG:" >> $LOG
echo "===================" >> $LOG
echo "" >> $LOG
echo "/sys/class/net:" >> $LOG
echo "===================" >> $LOG
ls /sys/class/net >> $LOG
echo "" >> $LOG
echo "lspci:grep Wireless" >> $LOG
echo "===================" >> $LOG
lspci|grep Wireless >> $LOG
echo "" >> $LOG
echo "lspci:grep Network controller" >> $LOG
echo "===================" >> $LOG
lspci|grep "Network controller" >> $LOG
echo "" >> $LOG
echo "Kernel:" >> $LOG
echo "===================" >> $LOG
grep wireless /lib/modules/`uname -r`/modules.dep >> $LOG
echo "" >> $LOG
echo "DMESG:" >> $LOG
echo "===================" >> $LOG
dmesg | tail -n10 >> $LOG

cat >> $MSG << EOF
Your log file is waiting on your dekstop!
EOF
messagebox
cleanup && exit
}

# Get the network device
get_device() {
ls -1 /sys/class/net |  sed '/lo/d' > $MEN
echo "Get_device_info" >> $MEN
menubox "Please select a network device: "
IFACE=${ANSW}

if [ "$IFACE" = "Get_device_info" ]; then
   get_device_info
   get_device
fi
rm $MEN $MENU > /dev/null 2>&1
ifconfig $IFACE up > /dev/null 2>&1
}

# Some ip advice
get_ip_advice() {
cat >> $MSG << IPA
IP ADDRESS ADVICE

The most common method is to obtain your IP address
through a DHCP server. Most routers act as DHCP server so
if you are not sure what to choose, then i recommend you
choose DHCP (Dynamic Host Control Protocol).

If you are not sure of the address of your router, then
when asked for it try some of the common address:
192.168.0.1
192.168.1.1
10.1.1.1
---------------------------------------------------

IPA
messagebox
rm $MEN $MENU > /dev/null 2>&1
}

# Get ip address method
get_ip() {
echo "DHCP_Server" > $MEN
echo "Manual_Entry" >> $MEN
echo "Get_some_help" >> $MEN
menubox "How will you obtain your IP address?"
IPTMP=${ANSW}

case $IPTMP in
   "DHCP_Server" )
        DHCP="yes"
        ;;
    "Manual_Entry")
        MANUAL=0
        inputbox "Please enter your preferred IP address: " "192.168.X.XXX"
        IP=${INPUTANSW}
        echo "ifconfig $IFACE $IP" >> $FILE
        inputbox "Please enter the IP address of your router: " "192.168.X.XXX"
        ROUTER=${INPUTANSW}
        echo "route add default gw $ROUTER $IFACE" >> $FILE
        inputbox "Enter the ip address of the DNS service: " $ROUTER
        DNS=${INPUTANSW}
        echo "echo "nameserver $DNS" > /etc/resolv.conf" >> $FILE
        # Disabling dhcpcd service
        cp /etc/rc.d/rc.inet1 $INET
        sed -i $INET -e 's/echo/#echo/g'
        sed -i $INET -e 's/for/#for/g'
        sed -i $INET -e 's@/sbin@#/sbin@g'
        sed -i $INET -e 's/done/#done/g'
        ;;
    "Get_some_help")
        get_ip_advice
        get_ip
        ;;
esac
rm $MEN $MENU > /dev/null 2>&1

}

# Start the wireless scanning
wireless_scan() {
( iwlist $IFACE scan > $TMP/wifi$$ ) | Xdialog --title "$TITLE" --no-buttons --no-close --infobox "Scanning ..." 4 50
grep ESSID $TMP/wifi$$ | awk -F: '{print$NF}' > $MEN
echo "Hidden_Network" >> $MEN
menubox "Choose the wifi network to which you wish to connect: "
# Remove the commas from the SSID or wrong KEY is generated
SSID=`echo $ANSW|sed 's/\"//'|sed 's/\"//'`

# If network is not hidden do a quick scan and give some advice
# to the user about which encryption to choose at next stage
if [ "$SSID" != "Hidden_Network" ]; then
   ENWPA=`sed -n '/'"$SSID"'/,/Cell/p' $TMP/wifi$$ | egrep 'IE: WPA|802.11i/WPA2'`
   if [ -n "$ENWPA" ]; then
     echo "It appears $SSID is using WPA/WPA2 encryption. \nPlease try this first at next screen" > $MSG
     messagebox
        else
     grep -B4 "$SSID" $TMP/wifi$$|grep -v $SSID > $TMP/wep$$
     sed -n '/'"$SSID"'/,/Cell/p' $TMP/wifi$$ >> $TMP/wep$$
     ENWEP=`grep 'Encryption key' $TMP/wep$$ | cut -d ":" -f2`
     if [ "$ENWEP" = "on" ]; then
     echo "It appears $SSID is using WEP encryption. \nPlease try this first at next screen" > $MSG
     messagebox
       else
     echo "It appears $SSID is an open network. \nPlease try this first at next screen" > $MSG
     messagebox
     rm $TMP/wep$$
   fi
  fi
  rm $TMP/wifi$$
      else
   inputbox "Please provide the name (ESSID) of your hidden AP" "type essid here"
   SSID=${INPUTANSW}
   Xdailog --title "$TITLE" --backtitle "Choose YES if unsure" --yesno "scan_ssid=1 is default but some drivers don't support it.\nIn this case ap_mode=2 is required (and safer). \n\nWould you like to use ap_mode=2?"
   [ $? -eq 0 ] && SCAN=0
fi

Xdialog --title "$TITLE" --menubox "Choose an encryption mode for your wireless device: " 0 0 7 \
1 "Open network (no encryption)" 2 "WEP encryption (fairly weak encryption)" 3 "WPA/WPA2 (strongest encryption)" 2> $DMP
ENC=`cat $DMP`


case $ENC in
  1 ) ENCR="OPEN"
     setup_open_network
      ;;
  2 ) ENCR="WEP"
     setup_wep_network
      ;;
  3 ) ENCR="WPA"
     setup_wpa_network
      ;;
esac
}

setup_open_network() {

echo "# Plaintext (no encryption) network" > $SUPPLICANT
echo "ctrl_interface=/var/run/wpa_supplicant" >> $SUPPLICANT
if [ "$SCAN" = "0" ]; then
   echo "ap_scan=2" >> $SUPPLICANT
fi
echo "network={" >> $SUPPLICANT
if [ -n "$HOC" ]; then echo "mode=1" >> $SUPPLICANT; fi
echo "scan_ssid=1" >> $SUPPLICANT
# Put commas back on SSID
SSID=`echo "\"$SSID"\"`
echo "ssid=$SSID" >> $SUPPLICANT
echo "key_mgmt=NONE" >> $SUPPLICANT
echo "}" >> $SUPPLICANT
sed -i $SUPPLICANT -e s/ssid="$SSID"/ssid='"'"$SSID"'"'/g
echo "#wpa_supplicant -Dwext -i$IFACE -c /etc/wpa_supplicant.conf > /dev/null 2>&1 &" >> $FILE
}

setup_wep_network() {
inputbox "Please provide the WEP key in HEX format: \n E.g 751E51F12091ACAA2D9AD3E2F0" "Type wep key" 
KEY=${INPUTANSW}
echo "# Static WEP key" > $SUPPLICANT
echo "ctrl_interface=/var/run/wpa_supplicant" >> $SUPPLICANT
if [ "$SCAN" = "0" ]; then
     echo "ap_scan=2" >> $SUPPLICANT
fi
echo "network={" >> $SUPPLICANT
if [ -n "$HOC" ]; then echo "mode=1" >> $SUPPLICANT; fi
echo "scan_ssid=1" >> $SUPPLICANT
# Put commas back on SSID
SSID=`echo "\"$SSID"\"`
echo "ssid=$ssid" >> $SUPPLICANT
echo "key_mgmt=NONE" >> $SUPPLICANT
echo "wep_key0=$key" >> $SUPPLICANT
echo "wep_tx_keyidx=0" >> $SUPPLICANT
echo "}" >> $SUPPLICANT
sed -i $SUPPLICANT -e s/ssid="$SSID"/ssid="$SSID"/g
echo "#wpa_supplicant -Dwext -i$IFACE -c /etc/wpa_supplicant.conf > /dev/null 2>&1 &" >> $FILE
}

setup_wpa_network() {
Xdialog --title "$TITLE" --password --inputbox "Please provide the WPA/WPA2 password: " 0 0 2> $DMP
KEY=`cat $DMP`
rm $DMP

PSK=`wpa_passphrase "$SSID" "$KEY" | grep psk=[a-f,0-9] |tail -n1| cut -d '=' -f 2`

echo "# WPA/WPA2 both TKIP and CCMP" > $SUPPLICANT
echo "ctrl_interface=/var/run/wpa_supplicant" >> $SUPPLICANT

if [ "$SCAN" = "0" ]; then
     echo "ap_scan=2" >> $SUPPLICANT
fi

echo "network={" >> $SUPPLICANT
if [ -n "$HOC" ]; then echo "mode=1" >> $SUPPLICANT; fi
echo "scan_ssid=1" >> $SUPPLICANT

# Put commas back on SSID
SSID=`echo "\"$SSID"\"`
echo "ssid=$SSID" >> $SUPPLICANT
echo "key_mgmt=WPA-PSK" >> $SUPPLICANT
echo "pairwise=CCMP TKIP" >> $SUPPLICANT
echo "group=CCMP TKIP" >> $SUPPLICANT
echo "psk=$PSK" >> $SUPPLICANT
echo "}" >> $SUPPLICANT
#sed -i $SUPPLICANT -e s/ssid="$SSID"/ssid="$SSID"/g
echo "#wpa_supplicant -Dwext -i$IFACE -c /etc/wpa_supplicant.conf > /dev/null 2>&1 &" >> $FILE
}


# A quick test of adhoc connection
test_adhoc() {
ping -c3 $HOC > $DMP
}

# Check internet connection
check_net () {
infobox "Waiting for network to set before testing..." 5000
if (wget --spider --force-html --inet4-only http://www.google.com >/dev/null 2>&1); then
CONNECTION="success"
fi
}

# Short help file
help_file() {
cat >> $MSG << EOF
PORTEUS NETWORK TOOL

This tool is to be used to setup your network connection.
After the network has been setup and an internet connection
is established you will have the option of creating a module
that can be placed in your /modules folder. This module will
be activated at each boot and the contents of rc.local will
be run ... connecting you to your network.

If you experience any problems please run the system log
generator and create a thread at the Porteus forum with a
request for assistance, and the contents of your log file
which is created on the desktop.
EOF
messagebox
unset MSG
main_menu
}


# Initial directory setup
cleanup
rm /root/pns-tool-configs.xzm > /dev/null 2>&1
rm -r /etc/dhcpc/* > /dev/null 2>&1
rm -r /var/run/wpa_supplicant/ > /dev/null 2>&1


mkdir -p $DIR/etc/rc.d
mkdir $TMP

kill_wifi() {
# Killing running instances of dhcpcd and wpa_supplicant
killall dhcpcd > /dev/null 2>&1
killall wpa_supplicant > /dev/null 2>&1
}

main_menu() {
# Initial menu
Xdialog --title "$TITLE" --center --menubox "$DATE \n\nWelcome to the Porteus Network Setup tool: " 0 0 9 \
1. "Read the help file" \
2. "Connect computer 2 computer" \
3. "Setup wireless network" \
4. "Setup wired network" \
5. "Generate a system log" \
6. "Exit the application" 2> $DMP
chkbut
catch && MM=${ANSW}

# Main menu case
case $MM in
  1.) help_file
      ;;
  2.) ADHOC=0
      kill_wifi
      get_device
      get_ip
      inputbox "Enter the IP of your target computer" "192.168.X.XXX"
      HOC=${INPUTANSW}
      wireless_scan
      
      ;;
  3.) WIFI=0
      kill_wifi
      get_device
      get_ip
      wireless_scan
      ;;
  4.) WIRED=0
      kill_wifi
      get_device
      get_ip
      ;;
  5.) generate_log
      ;;
  6. ) exit
      ;;
esac
}
main_menu
# Ask user to review config files before testing
#cat >> $MSG << EOF
#You will now have a chance to check the config files 
#and make any changes you think are necessary. After 
#making any changes click OK to continue.
#EOF
#messagebox

# Open files for editing before writing to $DIR
#Xdialog --title "$TITLE" --no-cancel --ok-label Continue \
#--editbox $FILE 30 90 2> $RCLOCAL
#Xdialog --title "$TITLE" --no-cancel --ok-label Continue \
#--editbox $SUPPLICANT 30 90 2> $WPASUPPLICANT


cp $FILE $RCLOCAL > /dev/null 2>&1
cp $SUPPLICANT $WPASUPPLICANT > /dev/null 2>&1

# Make rc.local executable
if [ -e $RCLOCAL ]; then
    chmod +x $RCLOCAL
    #$RCLOCAL & > /dev/null 2>&1
fi

if [ "$WIFI" = "0" ]; then 
    sed -i $RCLOCAL -e 's/#wpa_supplicant/wpa_supplicant/g'
fi

# Start wireless before giving user a message
# This will waste some time while dhcp initializes
if [ -e $WPASUPPLICANT ]; then
    wpa_supplicant -c $WPASUPPLICANT -i $IFACE -D wext &
    Xdialog --title "$TITLE" --no-buttons --infobox "Initialising wpa_supplicant" 5 60 5000
fi

if [ "$ADHOC" = "0" ]; then
( ping -c3 $HOC > $DMP ) |
Xdialog --title "$TITLE" --no-buttons --infobox "Testing the connection ..." 0 0 0
CHKCON=`grep statistics $DMP`
  if [ "$CHKCON" = "" ]; then
     Xdialog --title "$TITLE" --msgbox "Sorry, it appears there is no connection. We cannot continue" 0 0
     cleanup && exit
  fi
fi

# Start DHCP or copy resolv
if [ "$DHCP" = "yes" ]; then
infobox "Initialising DHCP interface now..." 4000
( dhcpcd $IFACE ) | infobox "Waiting for carrier to acknowledge..." 0
fi

cat >> $MSG << EOF
Time to check if your network connection is working. 

Press OK to proceed.
EOF
messagebox
chkbut

check_net
infobox "Testing internet connection now..." 4000

if [ -z "$CONNECTION" ]; then
   echo "Please double check that you are connected. \nA log will be placed on your desktop so you can seek help from the Porteus forum\nif there is a problem." >> $MSG
   messagebox
   generate_log
   exit
      else
   yesno "SUCCESS! YOU HAVE INTERNET." "All the required files have been generated in $DIR. \n\nWould you like to make a Porteus module from the required files?"
   if [ $? -eq 1 ]; then
      rm -rf $TMP
      exit
         else
      ( dir2xzm $DIR /$pth/Desktop/zzz-pns-network.xzm ) | infobox "Creating module now ....." 0
      infobox "Your module is on the desktop!" 4000 &
   fi
fi


