#!/bin/sh
path="${0%/*}"
. "$path/inc.sh"

usage () {
	die 'gwmodem testsetup [-f|--force] -- [sim1 apn] [sim2 apn]'
}

ignore=false
while : ; do
	case "$1" in
		-f|--f|--force)
			# ignore existing setup
			ignore=true
		;;
		--)
			shift
			break
		;;
		-*)
			usage
		;;
		*)
			break
		;;
	esac
	shift
done

apn1="${1:-tele2}"; shift;
apn2="${1}"; shift;

setupExists() {
	$ignore && return 1
	test -e "${sim1conf}" -o -e "${sim2conf}" && return 0
	return 1
}

simconf() {
	# $1: apn
	# $2: file
	[ -z "${1}" ] && return
	case "${1}" in
		tele2) apn='internet.tele2.ee'
		;;
		stele2|st2) apn='static.tele2.ee'
		;;
		telia) apn='internet.emt.ee'
		;;
		*) apn="${1}"
	esac
	cat > "${2}" <<-EOF
		# testsetup
		APN='${apn}'
		NETWORK=auto
	EOF
}

initGPIO() {
	if canSwitchSIM; then
		$GPIO -e MODEM_SIM1
		$GPIO -e MODEM_SIM2
		$GPIO -e MODEM_SIM_SELECT
	fi
	$GPIO -e RST_MODEM
	$GPIO -e MODEM_PWR
}

ppp0() {
	ip link show ppp0 &>/dev/null
}

setupGW() {
	if ppp0; then
		ip route del default
		ip route add default scope link dev ppp0
	else
		die "ppp0 does not exist"
	fi
}

wait_for_ppp0() {
	count=0
	while [ $((count++)) -lt 30 ] && ! ppp0; do sleep 2; done
}

run() {
	setupExists && die "Another setup already exists"
	simconf "${apn1}" "${sim1conf}"
	simconf "${apn2}" "${sim2conf}"
	initGPIO
	/etc/init.d/S42pppd restart
	wait_for_ppp0
	setupGW
}

run

