#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Chillispot Auto-Authentication script
# Copyright (c) Priit Laes (plaes plaes org)
# http://plaes.org/blog/2009/12/12/chillispot-login-with-python-and-curl
import subprocess
import urllib, urllib2
import json
import hashlib
import binascii

HOST="http://172.17.0.1:3990/json/"
USER="XXXX"
PASS="YYYY"

def status():
    """Request connection status."""
    request = urllib2.Request(HOST + "status")
    try:
        res = urllib2.urlopen(request)
    except urllib2.URLError, error:
        print "Error occurred: ", error
        return
    return json.loads(res.read())

def login(data):
    """Try to log in."""
    if 'challenge' not in data.keys():
        return
    hex = "00" + binascii.b2a_hex(PASS) + data['challenge']
    data = {
        "username": USER,
        "response": hashlib.md5(binascii.unhexlify(hex)).hexdigest()
    }
    # Unfortunately Python's httplib fails to parse response,
    # so we use curl instead:
    url = HOST + "logon?" + urllib.urlencode(data)
    subprocess.Popen("curl '" + url + "'",
        shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

def logoff():
    """Log off."""
    request = urllib2.Request(HOST + "logoff")
    try:
        urllib2.urlopen(request)
    except urllib2.URLError, error:
        print "Error occurred: ", error
        return

if __name__ == '__main__':
    data = status()
    # Check whether we need to log in:
    if data['clientState'] == 0:
        login(data)
    else:
        # Check session and idle timeout
        sess_expire = data['session']['sessionTimeout']
        idle_expire = data['session']['idleTimeout']
        sess = data['accounting']['sessionTime']
        idle = data['accounting']['idleTime']
        if sess > sess_expire*0.95 or idle > idle_expire*0.95:
            # We should re-login just in case...
            logoff()
            login(status())
