#!/usr/bin/env bash

set -e

lv=501071w21
url="https://www.math.tugraz.at/onlinekreuze/onlinekreuze.phtml?lv=$lv"
curl="curl -s"
session=$($curl $url | htmlq --attribute value 'form[name=loginform] input[name=session]')

login="$($curl $url \
	--data-urlencode "username_plain=$USER" \
	--data-urlencode "password_plain=$PASS" \
	--data-urlencode "session=$session" \
	--data-urlencode "iv=" \
	--data-urlencode "lv=$lv" \
	--data-urlencode "admin=false" \
	--data-urlencode "inactive=off" \
	--data-urlencode "matrikelnummer=" \
	--data-urlencode "submit=Einloggen")"
echo $login | grep Ausloggen >/dev/null

username=$(echo $login | htmlq --attribute value 'form input[name=username]' | head -n1)
password=$(echo $login | htmlq --attribute value 'form input[name=password]' | head -n1)
session=$(echo $login | htmlq --attribute value 'form input[name=session]' | head -n1)
iv=$(echo $login | htmlq --attribute value 'form input[name=iv]' | head -n1)
lv=$(echo $login | htmlq --attribute value 'form input[name=lv]' | head -n1)
admin=$(echo $login | htmlq --attribute value 'form input[name=admin]' | head -n1)
inactive=$(echo $login | htmlq --attribute value 'form input[name=inactive]' | head -n1)
matrikelnummer=$(echo $login | htmlq --attribute value 'form input[name=matrikelnummer]' | head -n1)
submit=$(echo $login | htmlq --attribute value 'form input[name=submit]' | head -n1)

stand="$($curl $url \
	--data-urlencode "action=showstand" \
	--data-urlencode "username=$username" \
	--data-urlencode "password=$password" \
	--data-urlencode "session=$session" \
	--data-urlencode "iv=$iv" \
	--data-urlencode "lv=$lv" \
	--data-urlencode "admin=$admin" \
	--data-urlencode "inactive=$inactive" \
	--data-urlencode "matrikelnummer=$matrikelnummer" \
	--data-urlencode "submit=$submit")"

echo -n "Klausur: "
echo $stand | htmlq tr | grep Klausur | grep -Eo '[0-9]+'

