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

/*
 * cp_get_session [cpzone=....] [ip=... [mac=...]] [username=...]
 * output on stdout: list of sessionid (one by line)
 */

global $cpzone, $config;

$ip = $mac = $username = $cpzone = null;

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

if ( $ip != null ) {
	// check IP format (ipv4 only)
	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);
	}
}

require("captiveportal.inc");

function show_sessions($zone) {
	global $cpzone;
	$cpzone = $zone;
	$cpdb = captiveportal_read_db();
	foreach ($cpdb as $cpentry) {
		print $cpentry[5] . "\n";
	}
}

// check if cpzone is defined
if ( $cpzone == null ) {
	foreach ($config['captiveportal'] as $cpkey => $cp) {
		if ($cp['auth_method'] == 'saml') {
			show_sessions($cpkey);
		}
	}
} else {
	show_sessions($cpzone);
}

?>
