#!/bin/sh

username="youruser@SKYNET"
password="yourpassword"
bbox_addr="10.0.0.1"

# params
cookies=$(mktemp .bgc_cookie.XXXXXXXX)

month=$(date +%m)
prevmonth=$(expr $month - 1)
[ $prevmonth -eq 0 ] && prevmount=12

# wget options for cookies
wget_opts="-qnv --load-cookies "$cookies" --save-cookies "$cookies" --keep-session-cookies"

login() {
	postdata="form_login=${login}&form_password=${password}&Submit2=Connect"
	url="https://admit.belgacom.be/ecare-slf/index.cfm?function=customer.overview&amp;farg.prod_type=vp"
	wget $wget_opts --post-data "$postdata" "$url" -O /dev/null
}

get_volume() {
	url="https://admit.belgacom.be/ecare-slf/index.cfm?function=connection.getVolume"
	wget $wget_opts "$url" -O - | \
		sed -nr 's@.*<strong>([0-9]+\s+[GM]B)</strong>.*@\1@p' | \
		xargs | awk '{printf("%d %s / %d %s\n",$1,$2,$3,$4)}'
}

get_session_info() {
	url="http://192.168.1.1/"
	wget $wget_opts "$url" -O /dev/null
}

connect_handle() {
	handle="$1"
	if [ "$handle" = "disconnect" ]; then
		action="submit_button_conn_disconect"
	else
		action="submit_button_conn_connect"
	fi

	output=$(wget $wget_opts "http://${bbox_addr}/index.cgi" -O -)
	session_id=$(echo "$output" | sed -nr 's@.*<INPUT type=HIDDEN name="session_id" value="([^"]+).*@\1@ip')
	transaction_id=$(echo "$output" | sed -nr 's@.*<INPUT type=HIDDEN name="transaction_id" value="([^"]+).*@\1@ip')
	post_url=$(echo "$output" | sed -nr 's@.*<FORM name="form_contents" method=POST action="([^"]+).*@\1@ip')
	output=$(wget $wget_opts "http://${bbox_addr}/index.cgi?session_id=${session_id}" -O -)
	transaction_id=$(echo "$output" | sed -nr 's@.*<INPUT type=HIDDEN name="transaction_id" value="([^"]+).*@\1@ip')
	url="http://${bbox_addr}${post_url}"
	postdata="active_page=9057&session_id=$session_id&prev_page=0&page_title=Status&nav_stack_0=9057&mimic_button_field=${action}%3A+..&button_value=&transaction_id=${transaction_id}"
	url="http://192.168.1.1/index.cgi"
	wget $wget_opts --post-data "$postdata" "$url" -O /dev/null
}
connect() {
	connect_handle "connect"
}
disconnect() {
	connect_handle "disconnect"
}

get_connection_log() {
	month="$1"
	postdata="Month_id=$month&typeConnection=All&x=28&y=3"
	url="https://admit.belgacom.be/ecare-slf/index.cfm?function=connection.getHistory"
	wget $wget_opts --post-data "$postdata" "$url" -O - | \
		sed -nr -e 's@.*bg[0-9]{1,2}.*>(.*Kb|.*[0-9]{1,2}/[0-9]{1,2}/[0-9]{4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2})<.*@\1@p' | \
			#-e 's@.*([0-9]{1,2}h|[0-9]{2}m|[0-9]{2}s).*@\1@p' | \
		xargs -n 6 | while read date time uvol uunit dvol dunit; do
			printf "%10s %8s  %11s %2s   %11s %2s\n" $date $time $uvol $uunit $dvol $dunit
		done
}


echo -e "Disconnecting ...\n"
disconnect
sleep 5
echo -e "Reconnecting ...\n"
connect

rm -f "$cookies"
