#!/usr/bin/perl

use Getopt::Long;
use POSIX ":sys_wait_h";
# use strict;

my %lineOpt = ( );

my $rootId = `id -u`;
chomp $rootId;

my $isRoot = ($rootId eq 0);

my %lineOpt = { };
my $intf = 'eth1';

GetOptions("command-set-netip=s" => $lineOpt{'set-netip'}
	);
    

sub main() {
        my $pid = fork();
        if( not $pid){
		$SIG{CHLD} = 'IGNORE';
	
		setNetIP($lineOpt{'set-netip'}) 			if $lineOpt{'set-netip'}  ne "";
		
		sleep 1;
		exit 0;
	}
}

sub insertDataInFile {
    my ($file,$intf,$data) = @_;
    my $state = 0;
    my $intfFile = $file;
    my $newIntfFile = $file . "-new";
    if(! open (INTF, "<$intfFile")) {
        print STDERR "Cannot open file $intFile";
        return 0;
    }
    flock(INTF, 2); #exclusive lock
    if(! open (INTFW, ">$newIntfFile")) {
        print STDERR "Cannot open file $newIntfFile";
        close INTF;
        return 0;
    }
    my $EntryCnts = 0;
    while(my $line = <INTF>) {
        chomp $line;
        if ($line =~ /NETSETUP_END/) { 
            $EntryCnts++; 
            $state = 0; 
        }
        print INTFW "$line\n" unless $state == 1;
        if ($line =~ /NETSETUP_BEGIN/) {
            $state = 1;
            $EntryCnts++;
            print INTFW "$data\n";
        }
    }
    close INTF;
    close INTFW;
    if ( $EntryCnts != 2 ) {
        print STDERR "!! Did not find the correct entries in $intfFile\n";
        print STDERR "!! Have you added them correctly?\n";
        unlink $newIntfFile;
        return 0;
    }
    unlink $intfFile;
    rename $newIntfFile, $intfFile;
    return 1;
}

sub setNetIP() {
    my $cmd = pop;
    my ($ip,$subnet, $gateway,$intf) = split(/:/,$cmd);

    my $location = "/etc/network/";
    if (! $isRoot) {
        print STDERR "!! Cannot set fixed ip as non root user\n" ;
        return 0;
    }
    
    if(!($ip && $subnet && $gateway && $intf)) {
        print STDERR "!! Not all field are filled..\n";
        print STDERR "!! The following fields are needed: IP:SUBNET:GATEWAY:DNS1:DNS2\n";
        return 0;
    }

    print "Setting new IP.\n" unless $lineOpt{silent} == 1;

    my $data = 
        "auto $intf\n" .
        "iface $intf inet static\n" .
        "  address $ip\n" .
        "  netmask $subnet\n" .
        "  gateway $gateway";
    
    return 0 if ! insertDataInFile ($location . "interfaces", $intf, $data);
    return 1;
}

main;
exit 0;
