#!/usr/bin/ucode

let ubus = require('ubus').connect();
let uci = require('uci').cursor();

function restart() {
	system('/etc/init.d/spotfilter restart');
	system('/etc/init.d/uhttpd restart');
}

switch(ARGV[0]) {
case 'dump':
	let clients = ubus.call('spotfilter', 'client_list', { interface: 'hotspot'});
	printf('%.J\n', clients);
	break;
case 'clients':
	let clients = ubus.call('spotfilter', 'client_list', { interface: 'hotspot'});
	let res = {};
	let t = time();

	for (let c, val in clients) {
		res[c] = {
			status: val.state ? 'Authenticated' : 'Garden',
                        idle: val.idle || 0,
			time: val.data.connect ? t - val.data.connect : 0,
			ip4addr: val.ip4addr || '',
			ip6addr: val.ip6addr || '',
			packets_ul: val.packets_ul || 0,
			bytes_ul: val.bytes_ul || 0,
			packets_dl: val.packets_dl || 0,
			bytes_dl: val.bytes_dl || 0,
		};
	}
	printf('%.J\n', res);
	break;
case 'remove':
	ubus.call('spotfilter', 'client_remove', { interface: 'hotspot', address: ARGV[1] || ''});
	break;
case 'restart':
	restart();
	break;
case 'log':
	system('logread -f | grep uspot:');
	break;
case 'debugon':
case 'debugoff':
	uci.set('uspot', 'config', 'debug', 1);
	uci.commit();
	restart();
	break;
default:
	break;
}
