#!/bin/dash
# Tether to a bluetooth phone (specifically, Android phones)
# This is CLI so that it can be used on non-graphical systems
#
# Copyright (C) James Budiono 2015
# License: GNU GPL Version 3 or later.
#

TEXTDOMAIN=fatdog
. gettext.sh
Back="$(gettext 'Back')"
OK="$(gettext 'OK')"
CANCEL="$(gettext 'Cancel')"

### configuration
APPTITLE="$(gettext 'USB Tethering')"
XTERM="defaultterm"
BT_CONFIG=/var/lib/bluetooth # /etc/bluetooth/var in older fatdogs
ANS_FILE=/tmp/ans.$$          # output from dialog

############ helpers ##############
trap 'cleanup; exit;' 0 HUP INT TERM

cleanup() {
	[ -f /etc/resolv.conf.usb-backup ] &&
	mv /etc/resolv.conf.usb-backup /etc/resolv.conf
	[ $XPID ] && kill $XPID
	rm -f $ANS_FILE 
}

### make our life with dialog a bit easier
# input: $@, output: $ans, $?
dlg() {
	local ret
	dialog --ok-button "$OK" --cancel-button "$CANCEL" --backtitle "$APPTITLE" "$@" 2> $ANS_FILE; ret=$?
	ans=$(cat $ANS_FILE) # because ans can be multiple lines
	return $ret
}

### $*-msg to display
msgbox() {
	dlg --msgbox "$*" 0 0
}

### $*-msg to display
infobox() {
	dlg --infobox "$*" 0 0
}

### make sure we run as root - input $@
run_as_root() {
	if [ $(id -u) -ne 0 ]; then
		if [ $DISPLAY ]; then
			exec gtksu "$APPTITLE" "$0" "$@"
		else
			exec su -c "$0 $*"
		fi
	fi
}

### make sure we run in terminal - input: $@
run_in_terminal() {
	# check we're running in terminal, if not, re-exec
	if ! test -t 0; then
		# not on terminal, re-exec on terminal
		if [ $DISPLAY ]; then
			exec $XTERM -e "$0" "$@"
		else
			exit
		fi
	fi
}


#################### 

ui_choose_devices() {
	local p devices

	devices=""
	for p in $(ip link show | awk '/^[0-9]/ && /usb/ {sub(/:/,"",$2); print $2}'); do
		devices="$devices $p $p"
	done

	while true; do
		device=""
		eval dlg --no-tags --menu "'Choose interface to connect to.'" 0 0 0 \
		$devices \
		exit "Exit" || exit 0
		case $ans in
			exit) exit 0 ;;
			*) device=$ans; break ;;
		esac
	done
}

#$1-iface
get_ip() {
	while ! ip link show $1 > /dev/null 2>&1; do
		sleep 1
	done
	udhcpc -qi $1 >> $ANS_FILE 2>&1 $ANS_FILE
	{
	echo "===============" 
	echo "Connection is now ready."
	echo "Keep this window open to maintain connection."
	echo "Press EXIT to shutdown." 
	} >> $ANS_FILE
}

#$1-device
connect_now() {	
	cp /etc/resolv.conf /etc/resolv.conf.usb-backup
	echo "Connecting ... please accept request on your phone." > $ANS_FILE
	ifconfig $1 0.0.0.0 up
	get_ip $1 &
	XPID=$!
	dialog --tailbox $ANS_FILE 15 60
	kill $XPID 
	ifconfig $1 0.0.0.0 down
	mv /etc/resolv.conf.usb-backup /etc/resolv.conf
	XPID="" 
	return 0
}


### main
run_as_root
run_in_terminal
msgbox "Connect your phone using USB cable now, and enable tethering from its settings screen.
Press OK to continue."
while true; do	
	ui_choose_devices &&
	connect_now $device
done


