#!/usr/bin/env python

import datetime
import settings
import subprocess
import re

# format :
# 1298550966,2,10.42.1.2,52:54:00:4c:89:67,xxxxid:C8NQsm1Y3Gas9m0AMDhxU7UxCSI=|https://services-federation.renater.fr/test/idp,2fcbba4d21ef9c38,,,,

CP_DB_FILENAME = '/var/db/captiveportal.db'

def get_captive_portal_session(id = None, ip = None):
    db = open(CP_DB_FILENAME, 'r')
    for l in db:
        timestamp, n, pfip, mac, user, pfid, x1, x2, x3, x4 = l.split(',')
        if (id and pfid == id) or (ip and pfip == ip):
            db.close()
            nameid, idp = user.split('|')
            datetime_local = datetime.datetime.fromtimestamp(int(timestamp))
            return {
                    'timestamp': int(timestamp),
                    'datetime_local': datetime_local,
                    'n': int(n),
                    'ip': pfip,
                    'mac': mac,
                    'user': user,
                    'nameid': nameid,
                    'idp': idp,
                    'id': pfid,
                    }
    db.close()
    return None


def get_mac_from_ip(ip):
    '''pythonization of etc/inc/util.inc::arp_get_mac_by_ip'''
    cmd = '/sbin/ping -c 1 -t 1 %s' % ip
    try:
        p = subprocess.Popen(cmd.split(), close_fds=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
    except:
        pass
    cmd = '/usr/sbin/arp -n %s' % ip
    try:
        p = subprocess.Popen(cmd.split(), close_fds=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        mac = stdout.split()[3]
        if re.match('^[0-9A-F]{2}(?:[:][0-9A-F]{2}){5}$', mac, re.IGNORECASE):
            return mac
    except:
	pass
    return '00:00:00:00:00:00'


# TODO

def captive_portal_allow():
    pass

def captive_portal_disconnect():
    pass

