curl -s http://172.16.0.1 > /dev/null
salt=`curl -c /tmp/cookies.txt -s http://172.16.0.1/tmp/status.json | tail -n 1 | cut -d "\"" -f 4`
pw=`echo -n admin${salt} | md5sum | cut -d ' ' -f 1`
curl -c /tmp/cookies.txt -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "un=admin&pw=${pw}&csrftok=${salt}" -s http://172.16.0.1/login_act.cgi > /dev/null
login=`curl -b /tmp/cookies.text -s http://172.16.0.1/tmp/status.json | head -n 1 | cut -d "\"" -f 2`

if [ $login == "initpwd" ]; then
	initpwd=`curl -b /tmp/cookies.text -s http://172.16.0.1/tmp/status.json | tail -n 1 | cut -d "\"" -f 4`
	curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "newpw=admin&confirmpw=admin&csrftok1=${initpwd}&current_page=initpwd" -s http://172.16.0.1/chgpwd_act.cgi  > /dev/null
	chgpwd=`curl -b /tmp/cookies.text -s http://172.16.0.1/tmp/status.json | head -n 1 | cut -d "\"" -f 2`	
	if [ $chgpwd == "chgpwd" ]; then
		curl -s http://172.16.0.1 > /dev/null
		salt=`curl -c /tmp/cookies.txt -s http://172.16.0.1/tmp/status.json | tail -n 1 | cut -d "\"" -f 4`
		pw=`echo -n admin${salt} | md5sum | cut -d ' ' -f 1`
		curl -c /tmp/cookies.txt -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "un=admin&pw=${pw}&csrftok=${salt}" -s http://172.16.0.1/login_act.cgi > /dev/null
	fi;
fi;

# Set to Modem Mode
curl -b /tmp/cookies.txt -s http://172.16.0.1/set_devicemode.cgi > /dev/null
modem_token=`curl -b /tmp/cookies.txt -s http://172.16.0.1/tmp/status.json | tail -n 3 | head -n 1 | cut -d "\"" -f 4`
modem_flag=`curl -b /tmp/cookies.txt -s http://172.16.0.1/tmp/status.json | tail -n 1 | cut -d "\"" -f 6`
curl -b /tmp/cookies.txt -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "csrftok=${modem_token}&current_page=set_devicemode&${modem_flag}=1" -s http://172.16.0.1/post_action.cgi > /dev/null

# Set to External SIM
curl -b /tmp/cookies.txt -s http://172.16.0.1/set_cellular.cgi > /dev/null
sim_token=`curl -b /tmp/cookies.txt -s http://172.16.0.1/tmp/status.json | head -n 2 | tail -n 1 | cut -d "\"" -f 4`
sim_flag=`curl -b /tmp/cookies.txt -s http://172.16.0.1/tmp/status.json | grep SIM_SELECT | cut -d "\"" -f 24`
curl -b /tmp/cookies.txt -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "csrftok=${sim_token}&current_page=set_cellular&${sim_flag}=1" -s http://172.16.0.1/post_action.cgi > /dev/null

# Set AT_NMEA Mode on and reboot
curl -b /tmp/cookies.txt -s http://172.16.0.1/at_nmea.cgi > /dev/null
nmea_token=`curl -b /tmp/cookies.txt -s http://172.16.0.1/tmp/status.json | tail -n 2 | head -n 1 | cut -d "\"" -f 4`
nmea_flag=`curl -b /tmp/cookies.txt -s http://172.16.0.1/tmp/status.json | tail -n 1 | cut -d "\"" -f 6`
curl -b /tmp/cookies.txt -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "csrftok=${nmea_token}&current_page=at_nmea&${nmea_flag}=1&reboot=1" -s http://172.16.0.1/post_action.cgi > /dev/null