#!/usr/bin/perl
# Simple script to import network configuration 
# from a debian based system to ebox
use strict; 

use EBox;
use EBox::Global;
use EBox::Sudo qw(:all);

use constant INTERFACES => '/etc/network/interfaces';
use constant RESOLV     => '/etc/resolv.conf';
use constant DEFAULT_IFACE => 'eth0';
use constant DEFAULT_UPLOAD => '1024';
use constant DEFAULT_DOWNLOAD => '1024';
use constant DEFAULT_NAME => 'default';
use constant BASE_KEY => 'gatewaytable/keys/todo1111';


EBox::init();
my $global = EBox::Global->getInstance();

sub get_dns {
	
	unless (open(FD, RESOLV)) { 
		warn  "couldn't open " . RESOLV;
		return [];
	}

	my @dns;	
	for my $line (<FD>) {
		$line =~ s/^\s+//g;
		my @toks = split (/\s+/, $line);
		if ($toks[0] eq 'nameserver')	{
			push (@dns, $toks[1]);
		}
	}

	return @dns;
}

sub get_interfaces {
	
	unless (open(FD, INTERFACES)) { 
		warn  "couldn't open " . INTERFACES;
		return [];
	}

	my @interfaces;
	my $iface;
	my @fields = qw /address netmask gateway vlan-raw-device/;
	
	for my $line (<FD>) {
		$line =~ s/^\s+//g;
		my @toks = split (/\s+/, $line);
		if ($toks[0] eq 'iface' and $toks[2] eq 'inet')	{
			next if ($toks[1] eq 'lo');			
			push (@interfaces, $iface) if ($iface);
			$iface = { name   => $toks[1],
				   method => $toks[3]
				 };
		}
	  
	   if (grep((/^$toks[0]$/), @fields)) {
	    	$iface->{$toks[0]} = $toks[1]; 
	   }
	}
	push (@interfaces, $iface) if ($iface);

	return @interfaces;
}



my $network = $global->modInstance('network');

foreach my $iface (get_interfaces) {
	if ($iface->{name} =~ /^vlan/) {
		($iface->{'vlan-raw-device'}) or 
			die "vlan interface '$iface->{name}' needs a ".
			"raw-device declaration";
		$network->setIfaceTrunk($iface->{'vlan-raw-device'}, 1);
		my $vlan = $iface->{name};
		$vlan =~ s/^vlan//;
		$network->createVlan($vlan, undef, $iface->{'vlan-raw-device'});
	}
	if ($iface->{'method'} eq 'static') {
		$network->setIfaceStatic($iface->{'name'}, $iface->{'address'},
					 $iface->{'netmask'}, undef, 1);
		
		if ($iface->{'gateway'}){
			$network->set_string(BASE_KEY . '/ip',
				$iface->{'gateway'});
			$network->set_string(BASE_KEY . '/interface', 
				$iface->{'name'});
			$network->set_string(BASE_KEY . '/name', 
				DEFAULT_NAME);
			$network->set_bool(BASE_KEY . '/default', 1);
			$network->set_int(BASE_KEY . '/upload', 
				DEFAULT_UPLOAD);
			$network->set_int(BASE_KEY . '/download', 
				DEFAULT_DOWNLOAD);
		}
		
	} elsif ($iface->{'method'} eq 'dhcp') {
		$network->setIfaceDHCP($iface->{'name'}, 0, 1);
	}
}



my @dns    = get_dns();
for (0..2) {
	unless ($dns[$_]){
		$dns[$_] = "";
	}
}
$network->setNameservers($dns[0], $dns[1], $dns[2]);
$network->generateInterfaces();
$network->save();
root("/bin/cp " . INTERFACES . " " . EBox::Config::tmp . "interfaces");
root("/bin/chown ebox.ebox " . EBox::Config::tmp . "interfaces");
