#!/bin/bash

#	hupon 1.1 - HUPnet login script
#
#	Copyright Mikko Rauhala <mjr@iki.fi>, 2008, 2010, 2013
#
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar at
# http://sam.zoy.org/wtfpl/COPYING and reproduced here:
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#                    Version 2, December 2004
#
# Copyright (C) 2004 Sam Hocevar
#  14 rue de Plaisance, 75014 Paris, France
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long
# as the name is changed.
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
#
#  0. You just DO WHAT THE FUCK YOU WANT TO.

# README:

# This logs you onto HUPnet without a bloody browser.
# Optionally have ~/.huprc with LOGIN=foo and PASSWORD=bar
# If you don't, you will be asked. I recommend not to
# stick in that PASSWORD part, but put the option in anyway.

# Used to be called "huplog" but that was just silly.

# Changelog:

# 1.2:		Fixed to recognize the new login successful message.
# 1.1:		Fixed for the current login page and a "real" certificate.
#		Also removed HUPnet check since login page available
#		from elsewhere now too.
# 1.0:		We actually check if we are on HUPnet before proceeding.
#		Also, login (not password) can be given on the command line.
#		This will override the configuration file and always ask
#		for the password interactively.
# 0.9.1:	No tempfile for password anymore, since we're
#		using bashisms anyway and reading in the password
#		to a variable. We rely on the internal echo
#		not to give away the data to eavesdroppers.
# 0.9:		Initial release

LC_ALL=C
export LC_ALL

ohnoes()
{
	echo "$1" 1>&2
	exit 1
}

if [ "a$2" != a ]
then
	echo "Usage: hupon [user]" 2>&1
	exit
fi

if ! which curl > /dev/null
then
	ohnoes "curl is required for hupon, aborting"
fi

if [ -e $HOME/.huprc ]
then
	. $HOME/.huprc || ohnoes "failed to parse ~/.huprc, aborting"
fi

if [ "a$1" != a ]
then
	LOGIN="$1"
	LOGIN_OVERRIDE=1
fi

if [ "a$LOGIN" = a ]
then
	echo -n "Login: "
	read LOGIN
fi

if [ "a$LOGIN_OVERRIDE" = a1 ] || ! grep -q "^PASSWORD=" "$HOME/.huprc" 2> /dev/null
then
	echo -n "Password for $LOGIN: "
	read -s PASSWORD
	echo
	PW_INTERACTIVE=1
fi

if ! echo -n "$PASSWORD" | curl -x "" --data-urlencode "login=$LOGIN" --data-urlencode "pass@-" --data-urlencode "Origin=" --data-urlencode "Login=Login" https://login.hupnet.helsinki.fi/login.pl 2> /dev/null | grep -qi "Login successful"
then
	ohnoes "Login to HUPnet (probably) failed; check your password."
fi

exit
