#!/bin/sh -ef
# NAME=USB GPRS Modem Dialup
# DESCRIPTION=Test GPRS modem, connected using USB
# DESTROYS_HDD=false
# IS_INTERACTIVE=false
# POWEROFF_DURING_TEST=false
# VERSION=0.1
# TAGS=usb,gprs
# VAR=DEV:string:/dev/ttyUSB0:Name of device to test
# VAR=APN:string:internet.mts.ru:Cell service provider's Internet APN
# VAR=PPPD_TRIES:int:4:Number of tries to bring pppd up
# VAR=URL:string:img-fotki.yandex.ru/getx/10/photoface.359/sevastopol-foto_34661_L:URL to download (without http)
# VAR=MD5:string:ca530886183b06d0047e0655537327aa:MD5 of downloaded file
# VAR=DOWNLOAD_TRIES:int:3:Number of tries to download the file
# VAR=DOWNLOAD_MAX_TIME:int:60:Timeout for the whole download, sec
# VAR=SPEED:int:115200:Line speed

. /usr/share/inquisitor/functions-test

exit_handler()
{
	if [ -r "$TMP_DIR/pppd.lock" ]; then
		echo -n 'Stopping pppd'
		killall pppd
		sleep 5
		if pgrep pppd; then
			echo_failure
			echo -n 'Killing pppd'
			killall -KILL pppd
			sleep 1
			echo_success
		else
			echo_success
		fi
	fi
	[ -d "$TMP_DIR" ] && rm -rf "$TMP_DIR"
}

MODEM_INIT='AT+CGDCONT=1,\"IP\",\"internet.mts.ru\" OK'
PHONE="*99***1#"
					
# Create temporary directory
TMP_DIR=`mktemp -d`

TRIES=0
while [ "$TRIES" -lt "$PPPD_TRIES" ]; do
	TRIES=$(($TRIES+1))

	# Try to stop pppd if it is already running
	if [ -r "$TMP_DIR/pppd.lock" ]; then
		echo -n 'Stopping pppd'
		killall pppd
		sleep 5
		if pgrep pppd; then
			echo_failure
			echo -n 'Killing pppd'
			killall -KILL pppd
			sleep 1
			echo_success
		else
			echo_success
		fi
		rm -f "$TMP_DIR/pppd.lock"
	fi

	if pppd \
		connect 'chat -v ABORT "NO DIALTONE" ABORT "NO CARRIER" ABORT BUSY "" '"$MODEM_INIT"' ATDP'$PHONE' "CONNECT" ;' \
		crtscts \
		defaultroute \
		modem \
		updetach \
		mru 576 \
		ipcp-accept-local \
		ipcp-accept-remote \
		noipdefault \
		debug \
		usepeerdns \
		user mts \
		mtu 576 \
		novj \
		nobsdcomp \
		novjccomp \
		nopcomp \
		noaccomp \
		$DEV $SPEED; then
		touch $TMP_DIR/pppd.lock
	else
		echo "PPP connect failed after try $TRIES"
		continue
	fi

	# Downloading
	echo -n "Downloading file"
	curl --retry "$DOWNLOAD_TRIES" --max-time "$DOWNLOAD_MAX_TIME" http://$URL -o $TMP_DIR/download && echo_success || continue

	# MD5 check
	echo -n 'Checking MD5 sum'
	echo "$MD5  $TMP_DIR/download" >$TMP_DIR/checkfile
	md5sum -c $TMP_DIR/checkfile && echo_success || continue

	# Finish test successfully
	break
done

if [ -r "$TMP_DIR/checkfile" ]; then
	test_succeeded
else
	test_failed
fi
