#include "captive.h"


/* See captive_adduser.c for info.  This program just reads all the records into
   an array, sorts them by username, then prints them.  */




int main( int argc, char *argv[]) {

	GDBM_FILE dbf;
	datum key, nextkey;
	datum content;
	char command[200];
	time_t tp;

	int count;


	time( &tp );

	dbf = gdbm_open( "/var/smoothwall/mods/captive/captivedb", 512, GDBM_WRITER, S_IRWXU, NULL );

	count = 0;
	key = gdbm_firstkey ( dbf );
	if( key.dptr != NULL ) key.dptr[key.dsize] = '\0';   /* Add null term, just to be safe. */

	while ( key.dptr ) {

		content = gdbm_fetch( dbf, key );

		if( ((userinfo *)content.dptr)->logged_in_now == 1 ) {
printf( "Logging off %s ...\n", key.dptr );
			((userinfo *)content.dptr)->logged_in_now = 0;
			((userinfo *)content.dptr)->ip[0] = '\0';
			((userinfo *)content.dptr)->mac[0] = '\0';
			((userinfo *)content.dptr)->login_expires_at = 0;
			gdbm_store( dbf, key, content, GDBM_REPLACE );
		}

		free ( content.dptr );
		nextkey = gdbm_nextkey ( dbf, key );

       		free ( key.dptr );
		key = nextkey;
		if( key.dptr != NULL ) key.dptr[key.dsize] = '\0';   /* Add null term, just to be safe. */
	}

	gdbm_close( dbf );

        if( system("/sbin/iptables -t nat -F captive") != 0 ) { printf( "system() error with iptables\n" ); exit(0); }

        snprintf( command, 200, "/sbin/iptables -t nat -A captive -i eth0 -s 0/0 -d %s -p udp --dport 53 -j ACCEPT", argv[1] );
        if( system(command) != 0 ) { printf( "system() error with iptables\n" ); exit(0); }

	snprintf( command, 200, "/sbin/iptables -t nat -A captive -i eth0 -s 0/0 -d %s -p tcp --dport 82 -j ACCEPT", argv[1] );
        if( system(command) != 0 ) { printf( "system() error with iptables\n" ); exit(0); }

        snprintf( command, 200, "/sbin/iptables -t nat -A captive -i eth0 -s 0/0 -d %s -p tcp --dport 441 -j ACCEPT", argv[1] );
        if( system(command) != 0 ) { printf( "system() error with iptables\n" ); exit(0); }

        snprintf( command, 200, "/sbin/iptables -t nat -A captive -i eth0 -s 0/0 -d %s -p tcp --dport 222 -j ACCEPT", argv[1] );
        if( system(command) != 0 ) { printf( "system() error with iptables\n" ); exit(0); }

        if( system("/sbin/iptables -t nat -A captive -i eth0 -s 0/0 -p tcp --dport 80 -j REDIRECT --to-port 82") != 0 ) { printf( "system() error with iptables\n" ); exit(0); }
        if( system("/sbin/iptables -t nat -A captive -i eth0 -s 0/0 -j DROP") != 0 ) { printf( "system() error with iptables\n" ); exit(0); }

	if( system("/var/smoothwall/mods/captive/allow.sh") != 0 ) { printf( "system() error with allow.sh\n" ); exit(0); }



	post_to_log( EVENT_SYSTEM_FLUSH, "N/A", "N/A", "N/A", (long)tp );


	return 0;
}
