#!/usr/local/bin/php -f
<?php

/*
 * cp_allow ip=... username=... [mac=...] [attrs=...] ...
 * output on stdout: sessionid
 */

$ip = $username = $mac = null;
$attributes = Array();

array_shift($argv);
foreach ($argv as $arg) {
	list($name, $value) = explode('=', $arg, 2);
	switch($name) {
		case 'ip':
			$ip=$value;
			break;
		case 'username':
			$username=$value;
			break;
		case 'mac':
			$mac=$value;
			break;
		case 'nameid':
			$nameid=$value;
			break;
		default:
			$attributes[$name]=$value;
	}
}

// check IP format (ipv4 only for now)
if (! preg_match( '/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip)) { 
	exit(2);
}

if ( $mac == null ) {
	// search MAC in ARP cache
	require("util.inc");
	$mac=arp_get_mac_by_ip($ip);
}

// check MAC format
if (! preg_match( '/^([0-9A-F]{2}:){5}[0-9A-F]{2}$/i', $mac)) {
	exit(3);
}

// from /etc/inc/captiveportal.inc :
// portal_allow($clientip,$clientmac,$username,$password = null,
//              $attributes = null, $ruleno = null)  
require("captiveportal.inc");
@captiveportal_logportalauth( $username, $mac, $ip, "LOGIN", '(' . $nameid . ')' );
echo portal_allow( $ip, $mac, $username, null, $attributes );

?>
