#!/bin/sh

login=$(cat bgcpasswd | cut -d':' -f1)
password=$(cat bgcpasswd | cut -d':' -f2)

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

month=$(date +%m)
prevmonth=$(expr $month - 1)
[ $prevmonth = 0 ] && prevmonth=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 - | tee /tmp/foo.html | \
		sed -nr 's@.*<strong>([0-9]+\s+[GM]B\s*)?([0-9]+\s+[GM]B)</strong>.*@\1\2 / @p' | \
		xargs | egrep -o '[[:alnum:][:blank:]]+/[[:alnum:][:blank:]]+'
}

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 "Login in...\n"
login

echo "Volume used:"
get_volume
echo

echo "Connection Log for $(date -d2000${month}01 +%B) ($month):"
get_connection_log $month
echo

echo "Connection Log for $(date -d2000${prevmonth}01 +%B) ($prevmonth):"
get_connection_log $prevmonth
echo


rm -f "$cookies"
