#!/bin/bash
# -*- ENCODING: UTF-8 -*-

# picanet
#
# Configure the Internet connection.
#
# Copyright (c) 2013-2026: Alexis Puente Montiel   < pica (a) picalibre.org >
#
# Licensed according to GNU AGPL version 3.0.
#
# It is libre/free software; you can use, redistribute and/or modify it according to the terms of GNU AGPL as published by GNU, version 3.0, 19 November 2007.
#
# It is distributed in the hope that it will be useful, but without any warranty. Read GNU AGPL version 3.0 for additional details.
#
# A copy of GNU AGPL version 3.0 is available at /usr/share/doc/<software-package-name>/agpl-3.0.txt (additionally on Internet as text at https://www.gnu.org/licenses/agpl-3.0.txt and as HTML at https://www.gnu.org/licenses/agpl-3.0-standalone.html ).
#
# Note: Additionally to the official e-mails, picalibre.org is strictly the only official site for this software project, please consider using it to download, report bugs and contribute.
#
# Depends: bash, coreutils, dhcpcd-base | isc-dhcp-client | isc-dhcp-client-ddns | udhcpc, dialog | yad | yad-pica | zenity, gawk | mawk | original-awk, grep, ifupdown, inetutils-ping | iputils-ping, iproute2 | net-tools, iw | wireless-tools, rfkill, sed, sysvinit-utils (<<2.88dsf-59.3) | init-system-helpers, wget, wpasupplicant | iwd
# Recommends: menu, pica-skel, x11-xkb-utils
# Suggests: consolation | gpm


### SCRIPT VARIABLES ########################################

CNAME="picanet"
VERSION="1.3.1"
TITLE="PicaNet"
ICON="/usr/share/icons/picanet.png"

# Translations
if [ "$LANG" = "" ] ; then export $(cat /etc/default/locale | grep -a 'LANG=') ; fi
TEXTDOMAIN=picanet
TEXTDOMAINDIR=/usr/share/locale/

# Write errors to log
ERRORLOG="$HOME/.${CNAME}.log"
if [ -e "$ERRORLOG" ] ; then
	mv -f $ERRORLOG ${ERRORLOG}.ant
fi
if [ -e "$ERRORLOG" ] ; then rm -rf "$ERRORLOG" ; fi

for i in /etc/pica-global.dist /etc/pica-global.orig /etc/pica-global /etc/pica-global.local ~/.pica-global ~/pica-global ; do
	if [ -f "$i" ] ; then
	cat "$i"
	source "$i"
	source <(cat $i | sed -e "s/=\(YES\|Yes\|yes\|y\|SÍ\|SI\|Sí\|Si\|sí\|si\|S\|s\)/=Y/g" -e "s/=\(No\|no\|n\)/=N/g" -e "s/=\"\(YES\|Yes\|yes\|y\|SÍ\|SI\|Sí\|Si\|sí\|si\|S\|s\)\"/=Y/g" -e "s/=\"\(No\|no\|n\)\"/=N/g")
	fi
done
if [ "$DEBUG" = "Y" ] ; then
	set -xv
	DEBUG="Y"
else
	ERRORLOG="/tmp/.${CNAME}_$(id -nu).log"
	if [ -e "$ERRORLOG" ] ; then mv -f $ERRORLOG ${ERRORLOG}.ant ; fi
	if [ -e "$ERRORLOG" ] ; then rm -rf "$ERRORLOG" ; fi
fi
if [ "$DEBUG" = "" ] ; then DEBUG="N" ; fi
if [ "$DEBUG" != "N" ] ; then
exec > >(tee -a "$ERRORLOG") 2>&1
echo "$0" "$*" >> "$ERRORLOG"
echo "$CNAME" "$VERSION" >> "$ERRORLOG"
echo $(date +%Y-%m-%d_%H:%M:%S) $"Start" >> "$ERRORLOG"
echo "env:" >> "$ERRORLOG"
env >> "$ERRORLOG"
echo "set:" >> "$ERRORLOG"
set >> "$ERRORLOG"
#else
#exec 2>>"$ERRORLOG"
fi

# Description:
BDESCRIP=$"Configure the Internet connection."
LDESCRIP=$"$TITLE is a tool to configure the Internet connection."

# Documentation:
docu_info () {
echo "$CNAME ($VERSION) - $BDESCRIP"
echo 
echo $"Usage:" $CNAME [$"OPTIONS"]
echo 
echo $"Options:"
echo -e "$ODESCRIP"
echo 
echo $"'man $CNAME' for more information."
echo 
}
ODESCRIP=" -t""\t"$"Use terminal interface.""\n"" -k""\t"$"Use 'kdialog' if possible.""\n"" -y""\t"$"Use 'yad' if possible (by default in graphical sessions).""\n"" -z""\t"$"Use 'zenity' if possible.""\n"" -x""\t"$"Show help documentation."

while getopts tkyzx OPTION ; do
	case $OPTION in
		t )   T="Y" ; G="N"      ;;
		k )   SDIALOG="kdialog"  ;;
		y )   SDIALOG="yad"      ;;
		z )   SDIALOG="zenity"   ;;
		x )   docu_info ; exit 0 ;;
	esac
done


### DIALOG ########################################

#DEFAULTDIALOGLIST="yad zenity kdialog"
DEFAULTDIALOGLIST="yad zenity"

#if [ -t 0 ] ; then
if [ "$(setxkbmap 1>/dev/null 2>&1 ; echo $? )" -ne 0 ] ; then
	G="N" ; T="Y"
fi

if [ "$G" != "N" ] ; then
	
	if   [ "$SDIALOG" = "kdialog" ] ; then
		DIALOGLIST="kdialog yad zenity"
	elif [ "$SDIALOG" = "yad" ] ; then
		DIALOGLIST="yad zenity kdialog"
	elif [ "$SDIALOG" = "zenity" ] ; then
		DIALOGLIST="zenity yad kdialog"
	else
		DIALOGLIST="$DEFAULTDIALOGLIST"
	fi
	
	if [ "$DIALOGLIST" = "" ] ; then
		if [ "$DEFAULTDIALOGLIST" != "" ] ; then
			DIALOGLIST="$DEFAULTDIALOGLIST"
		else
			DIALOGLIST="yad zenity kdialog"
		fi
	fi
	
	if [ "$(command -v $DIALOGLIST)" = "" ] ; then
		G="N" ; T="Y"
	fi

fi


if [ "$G" = "N" ] ; then

	if [ "$(command -v dialog)" = "" ] ; then
		echo $"ERROR: No supported dialog is installed. $TITLE cannot continue."
		exit 1
	else
		
		DIALOG="dialog --cr-wrap --keep-window --output-fd 1"
		#DIALOG="dialog --cr-wrap --keep-window --output-fd 1 --no-lines --no-shadow"
		if [ "$TITLE" != "" ] ; then
			WICON="--backtitle $(echo $TITLE | sed 's| |-|g')"
		fi
		WTITLE="--title"
		WTEXT=""
		H="0"
		W="0"
		LH="0"
		CALENDAR="--calendar"
		DATEFORMAT="--date-format %Y-%m-%d"
		WTIME="--timebox"
		TIMEFORMAT="--time-format %H:%M:%S"
		DSEL="--dselect"
		FSEL="--fselect"
		WRITE="--inputbox"
		PREWRITE=""
		COLUMN=""
		PRINTCOLUMN1=""
		PRINTCOLUMN2=""
		HIDECOLUMN1=""
		HIDECOLUMN2=""
		#INPUTSEPARATOR="--column-separator"
		#OUTPUTSEPARATOR="--separate-output"
		MONOLIST="--menu"
		#MONOLIST="--radiolist"
		MULTIPLELIST="--separate-output --checklist"
		PRE=""
		POST="off"
		PRES=""
		POSTS="on"

		INFO="--msgbox"
		WAIT="--infobox"

		QYN="--yesno"
		QYNC="--yesno"
		WYN="--yesno"
		WCC="--yesno"
		WYNC="--yesno"
		WM="--msgbox"
		ERROR="--msgbox"

		FORM="--form"
		FORMT=""
		FORMSELPRE=""
		FORMSELPOST=""
		#FORMCALPRE=""
		#FORMCALPOST=""
		#FORMCLPRE=""
		#FORMCLPOST=""
		PRELAB1="1 1"
		POSTLAB1="1 10 999 0"
		PRELAB2="2 1"
		POSTLAB2="2 10 999 0"
		PRELAB3="3 1"
		POSTLAB3="3 10 999 0"

		YES="--yes-label"
		NO="--no-label"
		OK="--ok-label"
		CONTINUE="--ok-label"
		CANCEL="--cancel-label"
		EXTRABUTTON="--extra-button --extra-label"
	
	fi

else

	for i in $DIALOGLIST ; do

		if [ "$(command -v $i)" != "" ] ; then
	
			if [ "$i" = "yad" ] ; then
		
				if [ "$(yad --version | tail -n 1 | cut -d ' ' -f 1 | cut -d '.' -f 1)" -lt 2 ] ; then
					DIALOG="yad --center"  # --selectable-labels (bug in Yad < 2.0) https://github.com/v1cont/yad/blob/master/NEWS
				else
					DIALOG="yad --center --selectable-labels"  # --on-top
				fi
				if [ "$ICON" != "" ] ; then
					WICON="--window-icon $ICON"
				fi
				WTITLE="--title"
				WTEXT="--text"
				H=""
				if [ "$(yad --version | tail -n 1 | grep -aE ^'7.2')" != "" ] ; then
					W="--width=640"
				else
					W="--width=640 --text-width=640 --fixed"  # https://github.com/v1cont/yad/issues/107  https://github.com/v1cont/yad/issues/140
				fi
				LH=""
				CALENDAR="--calendar"
				DATEFORMAT="--date-format %Y-%m-%d"
				WTIME="--separator=\n --columns 3 --form"
				#TIMEFORMAT="--time-format %H:%M:%S"
				DSEL="--file --directory --filename"  # Deleted *-selection alias for --file in Yad 4.0
				FSEL="--file --filename"              # Deleted *-selection alias for --file in Yad 4.0
				WRITE="--entry"
				PREWRITE="--entry-text"
				COLUMN="--column="
				PRINTCOLUMN1="--print-column=01"
				PRINTCOLUMN2="--print-column=02"
				HIDECOLUMN1="--hide-column=01"
				HIDECOLUMN2="--hide-column=02"
				#INPUTSEPARATOR="--item-separator"
				#OUTPUTSEPARATOR="--separator="
				#MONOLIST="--entry"
				MONOLIST="--separator=\n --list --search-column=1 --no-headers"
				MONOLISTH="--separator=\n --list --search-column=1"
				MULTIPLELIST="--separator= --list --checklist --search-column=2 --no-headers"
				MULTIPLELISTH="--separator= --list --checklist --search-column=2"
				PRE="FALSE"
				POST=""
				PRES="TRUE"
				POSTS=""
				# standard gtk keybindings for next and previous search are ctrl+g and ctrl+shift+g while you can redefine them in gtk-keys.css for your theme  # https://github.com/v1cont/yad/issues/127
			
				INFO="--image=/usr/share/icons/picalibre/rm/play.png --button="$"OK"
				WAIT="--image=/usr/share/icons/picalibre/rm/play.png --no-buttons"
			
				QYN="--image=/usr/share/icons/picalibre/rm/question.png --button="$"Yes"":0 --button="$"No"":1"
				QYNC="--image=/usr/share/icons/picalibre/rm/question.png --button="$"Yes"":0 --button="$"No"":1 --button="$"Cancel"":1"
				WYN="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"Yes"":0 --button="$"No"":1"
				WCC="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"Continue"":0 --button="$"Cancel"":1"
				WYNC="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"Yes"":0 --button="$"No"":1 --button="$"Cancel"":1"
				WM="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"OK"
				ERROR="--image=/usr/share/icons/picalibre/rm/error.png --button="$"OK"
			
				FORM="--separator=\n --form"
				FORMT="--field"
				FORMSELPRE="--field"
				FORMSELPOST=":FL"
				FORMCALPRE="--field"
				FORMCALPOST=":DT"
				FORMCLPRE="--field"
				FORMCLPOST=":CB"
				PRELAB1=""
				POSTLAB1=""
				PRELAB2=""
				POSTLAB2=""
				PRELAB3=""
				POSTLAB3=""
			
				YES="--button"
				NO="--button"
				OK="--button"
				CONTINUE="--button"
				CANCEL="--button"
				EXTRABUTTON="--button"
		
			elif [ "$i" = "zenity" ] ; then
		
				DIALOG="zenity"
				if [ "$ICON" != "" ] ; then
					WICON="--window-icon $ICON"
				fi
				WTITLE="--title"
				WTEXT="--text"
				H=""
				W="--width=640"
				LH=""
				CALENDAR="--calendar"
				DATEFORMAT="--date-format %Y-%m-%d"
				WTIME="--separator : --forms"
				#TIMEFORMAT="--time-format %H:%M:%S"
				DSEL="--file-selection --directory --filename"
				FSEL="--file-selection --filename"
				WRITE="--entry"
				PREWRITE="--entry-text"
				COLUMN="--column="
				PRINTCOLUMN1="--print-column=01"
				PRINTCOLUMN2="--print-column=02"
				HIDECOLUMN1="--hide-column=01"
				HIDECOLUMN2="--hide-column=02"
				#INPUTSEPARATOR=""
				#OUTPUTSEPARATOR="--separator=\n"
				MONOLIST="--separator=\n --list --hide-header"
				MONOLISTH="--separator=\n --list"
				MULTIPLELIST="--separator=\n --list --checklist --hide-header"
				MULTIPLELISTH="--separator=\n --list --checklist"
				PRE="FALSE"
				POST=""
				PRES="TRUE"
				POSTS=""
			
				INFO="--info"
				WAIT="--info"
			
				QYN="--question"
				QYNC="--question"
				WYN="--question"
				WCC="--question"
				WYNC="--question"
				WM="--warning"
				ERROR="--error"
			
				FORM="--forms"
				FORMT="--add-entry"
				FORMSELPRE="--add-entry"
				FORMSELPOST=""
				FORMCALPRE="--add-calendar"
				FORMCALPOST=""
				if [ "$(zenity --version | cut -d '.' -f 1 )" -ge 3 ] || [ "$(zenity --version | sed 's|\.||g')" -ge 3102 ] ; then
					FORMCLPOST="--combo-values"
					FORMCLPRE="--add-combo"
				fi
				PRELAB1=""
				POSTLAB1=""
				PRELAB2=""
				POSTLAB2=""
				PRELAB3=""
				POSTLAB3=""
			
				# Zenity <3 does not support custom buttons.
				if [ "$(zenity --version | cut -d '.' -f 1 )" -ge 3 ] ; then
					YES="--ok-label"
					NO="--cancel-label"
					OK="--ok-label"
					CONTINUE="--ok-label"
					CANCEL="--cancel-label"
					#EXTRABUTTON=""
				fi
		
#			elif [ "$i" = "kdialog" ] ; then
#		
#				# CAUTION: All 'kdialog' (TDE, KDE Plasma 4, KDE Plasma 5, KDE Plasma 6,...) are included here!
#			
#				DIALOG="kdialog"
#				if [ "$ICON" != "" ] ; then
#					WICON="--icon $ICON"
#				fi
#				WTITLE="--title"
#				WTEXT=""
#				H=""
#				W=""
#				LH=""
#				# No "--calendar" in TDE-kdialog + No "--date-format" both TDE and Plasma = There is no usable version of kdialog for calendars
#				#CALENDAR="--calendar"
#				#DATEFORMAT="--date-format %Y-%m-%d"
#				#WTIME="--timebox"
#				#TIMEFORMAT="--time-format %H:%M:%S"
#				DSEL="--getexistingdirectory"
#				FSEL="--getsavefilename"
#				#FSEL="--getopenfilename"
#				WRITE="--inputbox"
#				PREWRITE=""
#				COLUMN=""
#				PRINTCOLUMN1=""
#				PRINTCOLUMN2=""
#				HIDECOLUMN1=""
#				HIDECOLUMN2=""
#				#INPUTSEPARATOR=""
#				#OUTPUTSEPARATOR="--separate-output"
#				MONOLIST="--menu"
#				#MONOLIST="--combobox"
#				#MONOLIST="--radiolist"
#				MULTIPLELIST="--separate-output --checklist"
#				PRE=""
#				POST="off"
#				PRES=""
#				POSTS="on"
#			
#				INFO="--msgbox"
#				WAIT="--msgbox"
#			
#				QYN="--yesno"
#				QYNC="--yesnocancel"
#				WYN="--warningyesno"
#				WCC="--warningcontinuecancel"
#				WYNC="--warningyesnocancel"
#				WM="--sorry"
#				ERROR="--error"
#			
#				# No "--form" in any kdialog version
#				#FORM="--form"
#				#FORMT=""
#				#FORMSELPRE=""
#				#FORMSELPOST=""
#				#FORMCALPRE=""
#				#FORMCALPOST=""
#				#FORMCLPRE=""
#				#FORMCLPOST=""
#				#PRELAB1=""
#				#POSTLAB1=""
#				#PRELAB2=""
#				#POSTLAB2=""
#				#PRELAB3=""
#				#POSTLAB3=""
#			
#				# TDE-kdialog does not support custom buttons.
#				if [ "$(kdialog --version | grep -a Qt | grep -aEo "[0-9]" | head -n 1)" -ge 4 ] || [ "$(kdialog --version | grep -aEi kdialog | grep -aEo "[0-9]" | head -n 1)" -gt 1 ] ; then
#					YES="--yes-label"
#					NO="--no-label"
#					OK="--continue-label"
#					CONTINUE="--continue-label"
#					CANCEL="--cancel-label"
#					EXTRABUTTON="--cancel-label"
#				fi
		
			else
		
				true
		
			fi
		
		if [ "$DIALOG" != "" ] ; then break ; fi
		
		fi

	done

fi

if [ "$DIALOG" = "" ] ; then
	echo $"ERROR: No supported dialog is installed. $TITLE cannot continue."
	exit 1
fi


### ROOT CHECK ########################################

#if [ "$(cat /etc/passwd | grep -aE ^$(whoami): | cut -d ':' -f 3 )" -ne 0 ] ; then
if [ "$(id -u)" -ne 0 ] ; then
	$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"$TITLE must be launched as SuperUser.\n\nCannot continue." $H $W
	exit 1
fi
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/trinity/bin


### BASICFUN ########################################

ESP=$(printf '\302\240')

fexit () {

#if [ "$(cat /etc/passwd | grep -aE ^$(whoami): | cut -d ':' -f 3 )" -eq 0 ] ; then
if [ "$(id -u)" -eq 0 ] && [ "$DEBUG" = "Y" ] ; then
	RECERRORLOG="$ERRORLOG"
	for i in $(cat /etc/passwd | awk -F ':' '{print $3,$1}' | sort -n | grep -aEi "00[0-9] " | awk '{print $2}') ; do AUSER=$(users | sed 's| |\n|g' | grep -aE "^$i$" | head -n 1) ; if [ "$AUSER" != "" ] ; then
		HOMEERRORLOG=/home/$i/.${CNAME}.log
		RECERRORLOG="$RECERRORLOG $HOMEERRORLOG "
		cp -v --remove-destination $ERRORLOG $HOMEERRORLOG
		if [ "$(id -nu $i)" != "" ] ; then chown $(id -nu $i):$(id -ng $i) $HOMEERRORLOG ; else chown 1000:1000 $HOMEERRORLOG ; fi
		chmod 600 $HOMEERRORLOG ; if [ "$(stat -c %U $HOMEERRORLOG)" != "$i" ] ; then chmod 666 $HOMEERRORLOG ; fi
		break
	fi ; done
fi

exit $1

}

ranm () {

	# Reactivate $NM
	if [ "$NM" != "" ] ; then
		for i in $NM ; do
			#if [ "$(command -v systemctl)" != "" ] ; then systemctl start $i.service ;
			if [ "$(command -v service)" != "" ] ; then
				service $i start
			elif [ -e "/etc/init.d/$i" ] ; then
				/etc/init.d/$i start
			else
				true
			fi
			sleep 3
		done
	fi

}

check_exit () {

TAILERRORLOG=$(cat "$ERRORLOG" | grep -aE "[a-zA-Z0-9\=\[]" | tail -n 10 )

echo $(date +%Y-%m-%d_%H:%M:%S)

ranm

$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"Stop due to error.\n\n$TAILERRORLOG\n" $H $W

fexit 1

}

# If error, "try again or exit" dialog window
result_error () {

$DIALOG $WICON $WTITLE "$TITLE" $WYN   $WTEXT $"ERROR. Do you want to try again?" $H $W

if [ "$?" -ne 0 ] ; then
	ranm ; fexit 1
else
	picanet_script
fi

}


### SCRIPT ########################################

unset NM

picanet_script () {

if [ "$(command -v nmcli)" != "" ] ; then
nmcli dev show >> "$ERRORLOG"
nmcli -f DEVICE,SLAVE,TYPE,STATE,ACTIVE,AUTOCONNECT,AUTOCONNECT-PRIORITY,READONLY,NAME,FILENAME connection show >> "$ERRORLOG"
fi

for i in connman network-manager wicd picanet ; do
	#if [ "$(command -v systemctl)" != "" ] ; then if [ "$(systemctl show $i | grep -a '=active')" != "" ] ; then NM=$(echo $NM $i) ; systemctl stop $i.service ;
	if [ "$(command -v service)" != "" ] ; then
		if [ "$(service $i status 2>/dev/null | grep -aEv ' not | inactive | off ')" != "" ] ; then NM=$(echo $NM $i) ; service $i stop ; fi
	elif [ -e "/etc/init.d/$i" ] ; then
		NM=$(echo $NM $i)
		/etc/init.d/$i stop
	else
		true
	fi
done


if [ "$(command -v ifconfig)" != "" ] ; then
	ifconfig -a >> "$ERRORLOG"
	DEVLIST="" ; for i in $(ifconfig -a | grep -aE "^[a-z]" | awk '{print $1}' | grep -aEiv avahi | sed 's|: .*||g' | sed 's|:$||g' | grep -aEiv "^lo$" | sort -u ) ; do DEVLIST="$DEVLIST $i $ESP" ; done
elif [ "$(command -v ip)" != "" ] ; then
	ip a >> "$ERRORLOG"
	DEVLIST="" ; for i in $(ip a | grep -aE "^[0-9]" | awk '{print $2}' | grep -aEiv avahi | sed 's|: .*||g' | sed 's|:$||g' | grep -aEiv "^lo$" | sort -u ) ; do DEVLIST="$DEVLIST $i $ESP" ; done
else
	check_exit
fi

DEV=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select a device.\n\nWired interfaces usually have names that start with the letter 'e' or 'usb' (such as 'eth0' or 'enp0s1' or 'eno0') while wireless ('WiFi') interfaces usually have names that start with the letter 'w' and sometimes 'm' or 'a' (such as 'wlan0' or 'wlp1s0' or 'wlo0', sometimes 'mlan0' or 'ath0').\n\nIf the wireless card is not shown in the following list, it probably requires non-free software (driver or firmware) to work (or it is damaged)." $H $W $LH $COLUMN $COLUMN $DEVLIST | head -n 1 )

if [ "$?" -ne 0 ] || [ "$DEV" = "" ] ; then
	ranm ; fexit 0
fi


if [ "$(command -v ifconfig)" != "" ] ; then
	#ifconfig -a | grep -aE "^[a-z]" | awk '{print $1}' | grep -aEiv avahi | sed 's|: .*||g' | sed 's|:$||g' | grep -aEiv "^lo$" | sort -u | while read i ; do ifconfig $i down ; done
	ifconfig $DEV up
	if [ "$?" -ne 0 ] ; then echo $"ERROR" ifconfig $DEV up ; result_error ; return ; fi
elif [ "$(command -v ip)" != "" ] ; then
	#ip a | grep -aE "^[0-9]" | awk '{print $2}' | grep -aEiv avahi | sed 's|: .*||g' | sed 's|:$||g' | grep -aEiv "^lo$" | sort -u | while read i ; do ip link set $i down ; done
	ip link set $DEV up
	if [ "$?" -ne 0 ] ; then echo $"ERROR" ip link set $DEV up ; result_error ; return ; fi
else
	check_exit
fi


if [ "$(command -v iwconfig)" != "" ] ; then
	TESTWL=$(iwconfig $DEV 2>>$ERRORLOG)
elif [ "$(command -v iw)" != "" ] ; then
	TESTWL=$(iw dev $DEV info 2>>$ERRORLOG)
else
	check_exit
fi


if [ "$TESTWL" != "" ] ; then

	rfkill unblock all

	ssid_sel () {

	GOOD=$"GOOD"
	MEDIUM=$"MEDIUM"
	BAD=$"BAD"

	if [ "$(command -v iwlist)" != "" ] ; then
		iwlist $DEV scan >> "$ERRORLOG"
		iwlist $DEV scan 1>/dev/null 2>&1 ; if [ "$?" -ne 0 ] ; then echo $"ERROR" iwlist $DEV scan ; result_error ; return ; fi
		SSIDLIST=$(iwlist $DEV scan | grep -aEio 'Cell |SSID:\".*\"|Quality=.*|.* Signal level=.* dBm|WEP|WPA' | sed 's|Quality=||g' | sed 's|Signal level=.*-||g' | sed 's| dBm|dBm|g' | tr "\n" " " | sed 's|Cell |\n|g' | awk '{if ($2 < 60) print $3"("$4") "$1"="$2"■■■■""'"$GOOD"'" ; else if ($2 < 70) print $3"("$4") "$1"="$2"■■■□""'"$MEDIUM"'" ; else if ($2 < 80) print $3"("$4") "$1"="$2"■■□□""'"$MEDIUM"'" ; else print $3"("$4") "$1"="$2"■□□□""'"$BAD"'"}' | grep -aEi "^SSID" | sed "s|^SSID:||g" )
	elif [ "$(command -v iw)" != "" ] ; then
		iw dev $DEV scan >> "$ERRORLOG"
		iw dev $DEV scan 1>/dev/null 2>&1 ; if [ "$?" -ne 0 ] ; then echo $"ERROR" iw dev $DEV scan ; result_error ; return ; fi
		SSIDLIST=$(iw dev $DEV scan | grep -aEio "^BSS |SSID: .*|signal: .*|WEP|WPA|WPS" | sed 's|\(SSID:\) \(.*\)|\1"\2"|g' | sed 's|.*signal:.*-||g' | sed 's| dBm|dBm|g' | tr "\n" " " | sed 's|BSS |\n|g' | awk '{if ($1 < 60) print $2"("$3") "$1"■■■■""'"$GOOD"'" ; else if ($1 < 70) print $2"("$3") "$1"■■■□""'"$MEDIUM"'" ; else if ($1 < 80) print $2"("$3") "$1"■■□□""'"$MEDIUM"'" ; else print $2"("$3") "$1"■□□□""'"$BAD"'"}' | grep -aEi "^SSID" | sed "s|^SSID:||g" | sed 's|(WPS)|(WPA)|g')
	else
		check_exit
	fi

	REFRESH=$"Refresh"
	
	PRESSID=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select a wireless net (SSID).\n\nNote: >-60 dBM is a good quality connection, from -60 to -80 is a medium quality connection, less than -80 dBM is a bad quality connection." $H $W $LH $COLUMN $COLUMN $SSIDLIST "$REFRESH" " " | head -n 1 )

	if [ "$?" -ne 0 ] || [ "$PRESSID" = "" ] ; then
		ranm ; fexit 0
	elif [ "$PRESSID" = "$REFRESH" ] ; then
		ssid_sel ; return
	else
		SSID=$(echo "$PRESSID" | cut -d '"' -f 2 )
		WP=$(echo "$PRESSID" | cut -d '"' -f 3 | sed 's|(||g' | sed 's|)||g')
	fi

	}

	ssid_sel || return 1

	if [ ! -e /etc/picanet-pw ] ; then
		touch /etc/picanet-pw
		chown 0:0 /etc/picanet-pw
		chmod 0600 /etc/picanet-pw
	fi

	PREPW=$(cat /etc/picanet-pw | grep -a "$SSID" | awk '{print $2}' | tail -n 1 )
	
	PW=$($DIALOG $WICON $WTITLE "$TITLE" $WRITE $WTEXT $"Please write the wireless ('WiFi') net password:" $H $W $PREWRITE "$PREPW")

	if [ "$?" -ne 0 ] ; then
		ranm ; fexit 0
	fi

#	if [ "$PW" = "" ] ; then
#		result_error ; return
#	fi

fi

	TEMPORAL=$"Temporal"
	PERSISTENT=$"Persistent"
	
	TMP=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select whether you want a temporary or persistent configuration." $H $W $LH $COLUMN $COLUMN "$TEMPORAL" " " "$PERSISTENT" " " | head -n 1 )

	if [ "$?" -ne 0 ] || [ "$TMP" = "" ] ; then
		ranm ; fexit 0
	fi


	$DIALOG $WICON $WTITLE "$TITLE" $OK " " $WAIT  $WTEXT $"Please wait..." $H $W &
	PIDDIALOGWL=$( echo $! )


	if [ "$TMP" = "$PERSISTENT" ] ; then
		
#		CHECKBUS=$(cat /sys/class/net/$DEV/device/modalias | cut -d ':' -f 1 )
#		if [ "$CHECKBUS" = "" ] ; then CHECKBUS=$(lshw -businfo -C net | grep -a " $DEV " | cut -d '@' -f 1 ) ; fi
#	
		if [ -s /etc/network/interfaces ] ; then
			cp -av /etc/network/interfaces /etc/network/interfaces_$(date +%Y%m%d_%H%M%S)
		else
cat > /etc/network/interfaces <<EOF
# This file describes the network interfaces available on your system
# and how to activate them. For more information, read interfaces(5).

auto lo
iface lo inet loopback

#auto /e*=e
#iface e inet dhcp

EOF
		fi
		
		CHECKINTERFACE=$(cat /etc/network/interfaces | grep -a " $DEV" )
		if [ "$CHECKINTERFACE" != "" ] ; then
			cat /etc/network/interfaces
			sed -i "/ $DEV$/,/^$/d" /etc/network/interfaces
			sed -i "/=$DEV$/,/^$/d" /etc/network/interfaces
			sed -i "/ $DEV /,/^$/d" /etc/network/interfaces
			cat /etc/network/interfaces
		fi
	
#		if [ "$CHECKBUS" = "usb" ] ; then
cat >> /etc/network/interfaces <<EOF
allow-hotplug $DEV
iface $DEV inet dhcp
EOF
#		else
#cat >> /etc/network/interfaces <<EOF
#auto $DEV
#iface $DEV inet dhcp
#EOF
#		fi
	
	fi

if [ "$TESTWL" != "" ] ; then

	if [ "$PW" = "" ] ; then
		if [ "$(command -v iwconfig)" != "" ] ; then
			iwconfig $DEV essid "$SSID"
			if [ "$?" -ne 0 ] ; then kill $PIDDIALOGWL 2>/dev/null ; echo $"ERROR" iwconfig $DEV essid "$SSID" ; result_error ; return ; fi
		
			if [ "$TMP" = "$PERSISTENT" ] ; then
			sed -i "s|iface $DEV .*|&\n    wireless-essid \"$SSID\"\n|g" /etc/network/interfaces
			fi
		
		elif [ "$(command -v iw)" != "" ] ; then
			iw dev $DEV connect "$SSID"
			if [ "$?" -ne 0 ] ; then kill $PIDDIALOGWL 2>/dev/null ; echo $"ERROR" iw dev $DEV connect "$SSID" ; result_error ; return ; fi
		
			if [ "$TMP" = "$PERSISTENT" ] ; then
			sed -i "s|iface $DEV .*|&\n    wireless-essid \"$SSID\"\n|g" /etc/network/interfaces
			fi
		
		else
			kill $PIDDIALOGWL 2>/dev/null
			check_exit
		fi

	elif [ "$WP" = "WEP" ] ; then
		if [ "$(command -v iwconfig)" != "" ] ; then
			iwconfig $DEV essid "$SSID" key s:"$PW"
			if [ "$?" -ne 0 ] ; then kill $PIDDIALOGWL 2>/dev/null ; echo $"ERROR" iwconfig $DEV essid "$SSID" key s:"$PW" ; result_error ; return ; fi
		
			if [ "$TMP" = "$PERSISTENT" ] ; then
			sed -i "s|iface $DEV .*|&\n    wireless-essid \"$SSID\"\n    wireless-key s:\"$PW\"\n|g" /etc/network/interfaces
			fi
		
		elif [ "$(command -v iw)" != "" ] ; then
			iw dev $DEV connect "$SSID" key 0:"$PW"
			if [ "$?" -ne 0 ] ; then kill $PIDDIALOGWL 2>/dev/null ; echo $"ERROR" iw dev $DEV connect "$SSID" key 0:"$PW" ; result_error ; return ; fi
		
			if [ "$TMP" = "$PERSISTENT" ] ; then
			sed -i "s|iface $DEV .*|&\n    wireless-essid \"$SSID\"\n    wireless-key 0:\"$PW\"\n|g" /etc/network/interfaces
			fi
		
		else
			kill $PIDDIALOGWL 2>/dev/null
			check_exit
		fi

	else

		if [ "$(command -v wpa_supplicant)" != "" ] ; then
			wpa_supplicant -B -i $DEV -D nl80211,wext,wired,none -K -c <(wpa_passphrase "$SSID" "$PW" )
			if [ "$?" -ne 0 ] ; then kill $PIDDIALOGWL 2>/dev/null ; echo $"ERROR" wpa_supplicant -B -i $DEV -D nl80211,wext,wired,none -K -c <(wpa_passphrase "$SSID" "$PW" ) ; result_error ; return ; fi
		
		elif [ "$(command -v iwctl)" != "" ] ; then
			iwctl -P "$PW" station $DEV connect "$SSID"
			if [ "$?" -ne 0 ] ; then kill $PIDDIALOGWL 2>/dev/null ; echo $"ERROR" iwctl -P "$PW" station $DEV connect "$SSID" ; result_error ; return ; fi
		
		else
			kill $PIDDIALOGWL 2>/dev/null
			check_exit
		fi
		
			# wpasupplicant works but iwd doesn't work using /etc/network/interfaces
			if [ "$TMP" = "$PERSISTENT" ] ; then
			sed -i "s|iface $DEV .*|&\n    wpa-ssid \"$SSID\"\n    wpa-psk \"$PW\"\n|g" /etc/network/interfaces
			fi
	fi

else

echo "" >> /etc/network/interfaces

fi

	kill $PIDDIALOGWL 2>/dev/null

	$DIALOG $WICON $WTITLE "$TITLE" $OK " " $WAIT  $WTEXT $"Please wait..." $H $W &
	PIDDIALOGDH=$( echo $! )

if [ "$(command -v dhclient)" != "" ] ; then
	dhclient -r $DEV
	dhclient $DEV
	if [ "$?" -ne 0 ] ; then kill $PIDDIALOGDH 2>/dev/null ; echo $"ERROR" dhclient $DEV ; result_error ; return ; fi
elif [ "$(command -v dhcpcd)" != "" ] ; then
	dhcpcd -k $DEV
	dhcpcd $DEV
	if [ "$?" -ne 0 ] ; then kill $PIDDIALOGDH 2>/dev/null ; echo $"ERROR" dhcpcd $DEV ; result_error ; return ; fi
elif [ "$(command -v udhcpc)" != "" ] ; then
	udhcpc -R -i $DEV
	udhcpc -i $DEV
	if [ "$?" -ne 0 ] ; then kill $PIDDIALOGDH 2>/dev/null ; echo $"ERROR" udhcpc $DEV ; result_error ; return ; fi
else
	echo $"ERROR" DHCP
fi

	kill $PIDDIALOGDH 2>/dev/null


if [ "$NM" != "" ] ; then
	$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"Do you want to reactivate $NM ?\n\nIf in doubt, select 'No/Cancel'." $H $W
	if [ "$?" -eq 0 ] ; then
		ranm
		if [ "$(command -v nmcli)" != "" ] ; then
		nmcli dev show >> "$ERRORLOG"
		nmcli -f DEVICE,SLAVE,TYPE,STATE,ACTIVE,AUTOCONNECT,AUTOCONNECT-PRIORITY,READONLY,NAME,FILENAME connection show >> "$ERRORLOG"
		fi
	fi
fi


ping -c 3 ftp.fau.de || ping -c 3 mirrorservice.org || ping -c 3 ftp.ch.debian.org
if [ "$?" -ne 0 ] ; then
	wget http://ftp.fau.de -O /dev/null || wget http://mirrorservice.org -O /dev/null || wget http://ftp.ch.debian.org -O /dev/null
	if [ "$?" -ne 0 ] ; then
		$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"No Internet connection. $TITLE failed! " $H $W
		ranm ; fexit 1
	else
		$DIALOG $WICON $WTITLE "$TITLE" $INFO  $WTEXT $"Connection successfully established." $H $W
		if [ "$SSID" != "" ] && [ "$PW" != "" ] && [ "$(cat /etc/picanet-pw | grep -a $SSID )" = "" ] ; then printf "$SSID""\t""$PW""\n" >> /etc/picanet-pw ; fi
		if [ -e /etc/picanet-pw ] ; then chown 0:0  /etc/picanet-pw ; fi
		if [ -e /etc/picanet-pw ] ; then chmod 0600 /etc/picanet-pw ; fi
		fexit 0
	fi
else
	$DIALOG $WICON $WTITLE "$TITLE" $INFO  $WTEXT $"Connection successfully established." $H $W
	if [ "$SSID" != "" ] && [ "$PW" != "" ] && [ "$(cat /etc/picanet-pw | grep -a $SSID )" = "" ] ; then printf "$SSID""\t""$PW""\n" >> /etc/picanet-pw ; fi
	if [ -e /etc/picanet-pw ] ; then chown 0:0  /etc/picanet-pw ; fi
	if [ -e /etc/picanet-pw ] ; then chmod 0600 /etc/picanet-pw ; fi
	fexit 0
fi

}

picanet_script
