#!/usr/bin/perl

use strict;
use CWeb::GetVars;
use CWeb::TemplProc;
use CWeb::Tools;
use Config::Sh;
use Config::Security;
use Config::List;
#use Data::Dumper;

my $gv = new CWeb::GetVars;
my $get = $gv->{FORM};
my $p = new CWeb::TemplProc;
my $conf_sec = new Config::Security;
my $fw = new Config::Sh("/etc/firewall/firewall.conf");
$fw->read();
my $sl = new Config::List("/etc/firewall/allow.list",
			  ["name","proto","sport","dport"]);
$sl->read();

# ------------------------- WEP + WPA Sec.  -------------------------

if ( $get->{ 'cmd' } eq "ok" ) {
    my $sec_mode = $get->{ 'sec_mode' } ;

    # WPA
    if ( $sec_mode =~ m/^\d/ ) {
		$conf_sec->sec_mode( 'wpa' , $sec_mode ) ;
		$conf_sec->sec_mode( $get->{ 'wpa_key_type' }, $get->{ 'wpa_key_content' } ) ;
		$conf_sec->sec_mode( 'ssid' ) ;
		$conf_sec->write() ;
    }

    # WEP
    elsif ( $sec_mode eq 'wep' ) {
		my $wep_env = {	
					'key1'		=> $get->{'wep_key_1'} ,
					'key2'		=> $get->{'wep_key_2'} ,
					'key3'		=> $get->{'wep_key_3'} ,
					'key4'		=> $get->{'wep_key_4'} ,
					'default'	=> $get->{'wep_default_key'}
		} ;
		$conf_sec->sec_mode( 'wep', $wep_env ) ;
		$conf_sec->sec_mode( 'ssid' ) ;
		$conf_sec->write() ;
    }

    # No Encryption
    elsif ( $sec_mode eq 'off' ) {
		$conf_sec->sec_mode( 'off' ) ;
		$conf_sec->sec_mode( 'ssid' ) ;
		$conf_sec->write() ;
    }
}

# Generate 4 WEP keys from passphrase
if ( $get->{ 'cmd' } eq 'generate' ) {

	my $phrase = $get->{ 'wep_phrase' } ;
	
	if ( $phrase ) {
		my @keys = $conf_sec->wep_generate( $phrase ) ;
		my $wep_env = {	
					'key1'		=> $keys[0] ,
					'key2'		=> $keys[1] ,
					'key3'		=> $keys[2] ,
					'key4'		=> $keys[3] ,
					'default'	=> $get->{'wep_default_key'}
		} ;
		$conf_sec->sec_mode( 'wep', $wep_env ) ;
		$conf_sec->sec_mode( 'ssid' ) ;
		$conf_sec->write() ;
	}
}

# ------------------------- END all Forms  -------------------------

my $sec_val = $conf_sec->values_get();
$sec_val->{FW_SERVICES} = $sl->{VARS};
$sec_val->{FW_SETTINGS} = $fw->{VARS};
$p->process_template( "templates/security_wlan.html", $sec_val );
#print "
";
#print Dumper($sec_val);
#print Dumper($get->{'cmd'});
#print "
";
