#!/bin/sh
# Copyright (c) 2014 The Linux Foundation. All rights reserved.
#echo "we are in 99-4g-attach: ACTION = $ACTION INTERFACE= $INTERFACE" > /dev/console
MODEMLIB=/usr/lib/modem
. ${MODEMLIB}/usbmodem_log.sh
. /lib/functions.sh

USB_IFS=$(uci get modem.modeminfo.ifs)
USB_IFNAME=$(uci get modem.modeminfo.ifname)
MANAGE_DEVS_CHAIN="manage_devs"
[ $INTERFACE = $USB_IFS ] && [ $ACTION = "ifup" ] && {
	config_load network
	local ifname=""
	local proto=""
	config_get ifname ${USB_IFS} "ifname"
	config_get proto ${USB_IFS} "proto"
	local ipaddr=`ip addr show $ifname |grep "inet " |cut -d' ' -f6`
	local mask=`ifconfig $ifname |grep Mask`
	local mask=${mask#*Mask:}	

	gw=`ubus call network.interface.${USB_IFS} status |grep nexthop |awk '{print $2}' |sed "/0.0.0.0/"d |sed "2,$"d |sed "s/,//g" |sed "s/\"//g"`

	syslog $LOG_PROTO_SETUP "connected. proto:$proto ip:$ipaddr mask:$mask gw:$gw"
	[ -n "$gw" ] || {
		echo "gw not ready" > /dev/console && return
	}
	# echo "test gw = $gw" > /dev/console
	tarVid=$(uci get modem.modeminfo.targetvid)
	tarPid=$(uci get modem.modeminfo.targetpid)
	defVid=$(uci get modem.modeminfo.defaultvid)
	defPid=$(uci get modem.modeminfo.defaultpid)

	#ZTE mtc 832FT  && ZTE TELE2 MF823D 
	[ $defVid = "19d2" ] && [ $defPid = "1225" ] && [ $tarVid = "19d2" ] && [ $tarPid = "1405" -o $tarPid = "1403" ] && { 
		cmd="curl -m 10 --header \"Referer: http://$gw/index.html\" \"http://$gw/goform/goform_set_cmd_process?goformId=SET_CONNECTION_MODE&ConnectionMode=auto_dial -S -v \""
	}

	# Quanta beeline 1k6E
	[ $defVid = "0408" ] && [ $defPid = "ea43" ] && [ $tarVid = "0408" ] && [ $tarPid = "ea45" ] && { 
		cmd="curl -m 10 -d \"connect=1\" \"http://$gw/cgi/connect.cgi -S -v \""
	}

		
	# ZTE TELE2 MF710 
	if [ $defVid = "19d2" -a $defPid = "1405" -a $tarVid = "19d2" -a $tarPid = "1405" ] ;then
		cmd="curl -m 10 --header \"Referer: http://$gw/index.html\" \"http://$gw/goform/goform_set_cmd_process?goformId=CONNECT_NETWORK -S -v \""
	fi
	
	# ZTE Megafon M100-3
	#[ $defVid = "19d2" ] && [ $defPid = "1225" ] && [ $tarVid = "19d2" ] && [ $tarPid = "1403" ] && { 
	#	cmd="curl -m 10 -G \"http://$gw/goform/goform_set_cmd_process?goformId=SET_CONNECTION_MODE&ConnectionMode=auto_dial -S -v \""
	#}

	echo "cmd = $cmd" > /dev/console
	[ -n "$cmd" ] || {
		echo "cmd=null" > /dev/console && return 
	}
	
	# add manage_devs rule to let CURL request pass
	iptables -w -I $MANAGE_DEVS_CHAIN 1 -o $USB_IFNAME -p tcp --dport 80 -j RETURN
	
	count=3
	while [ "$count" != 0 ]
	do
		eval "ret=\$($cmd)"
		echo $ret >> /dev/console
		echo $ret | grep -i -e ok -e success
		[ $? = 1 ] && {
			echo "http send not success" > /dev/console
			syslog 9 "http send not success"
			count=$((count-1))
			continue
		}
		echo "http send success" > /dev/console
		syslog 9 "http send success"
		break
	done
	
	# del manage_devs rule
	iptables -w -D $MANAGE_DEVS_CHAIN -o $USB_IFNAME -p tcp --dport 80 -j RETURN 2>/dev/null
}


