#!/usr/bin/perl -w

use strict;

if( @ARGV == 0) {
	usage();
} elsif(@ARGV == 1) {
	show($ARGV[0]);
} elsif(@ARGV == 2) {
	if($ARGV[1] eq "dhcp") {
		exit config_dhcp($ARGV[0]);
	} elsif($ARGV[1] eq "off") {
		exit config_off ($ARGV[0]);
	} else {
		usage();
		exit 1;
	}
} elsif (@ARGV == 3) {
	exit config_static(@ARGV);
} else {
	usage();
	exit 1;
}


sub usage
{
	print STDOUT <<EOF
Usage:
	config_nic <interface>
		Show the configuration of <interface>
	config_nic <interface> dhcp
		Config the interface by DHCP
	config_nic <interface> off
		Disable the interface
	config_nic <interface> <IP Address> <Mask>
		Config the interface static IP address
EOF

}
sub show
{
	my ($interface) = @_;
	
	print STDOUT "Interface = $interface\n";
	my $status = system("ifconfig $interface | grep UP >/dev/null 2>&1") >> 8;
	if($status == 0) {
		print STDOUT "Status = up\n";
	} else {
		print STDOUT "Status = down\n";
	}

	if( -e "/var/run/dhcpcd-$interface.pid") {
		print STDOUT "DHCP = yes\n";
	} else {
		print STDOUT "DHCP = no\n";
	}

	my $line = `ifconfig $interface | grep "inet addr" 2> /dev/null`;
	if(length $line > 0) {
		my @segments = split(/[ \t]+/, $line);
		my ($name, $value) = split(/:/, $segments[2]);
		print STDOUT "IP Address = $value\n";
		($name, $value) = split(/:/, $segments[4]);
		print STDOUT "Mask = $value\n";
	}
}
sub config_dhcp
{
	my ($interface) = @_;

	if( -e "/var/run/dhcpcd-$interface.pid") {
		system("dhcpcd -k $interface > /dev/null 2>&1");
		system("rm -rf /var/run/dhcpcd-$interface.pid &> /dev/null");
	}

	if (! -d "/etc/dhcpc") {
		system("mkdir -p /etc/dhcpc");
	}
	if (! -f "/etc/dhcpc/dhcpcd_$interface.cache") {
		system("touch /etc/dhcpc/dhcpcd-$interface.cache");
	}
	if (! -f "/etc/dhcpc/dhcpcd_$interface.info") {
		system("touch /etc/dhcpc/dhcpcd-$interface.info");
	}

	system("ifconfig $interface up &> /dev/null");
	my $ret = system("dhcpcd -t 5 $interface > /dev/null 2>&1") >> 8;
	if($ret == 0) {
		system("ifconfig $interface up &> /dev/null");
	}

	return $ret;
}

sub config_off
{
	my ($interface) = @_;
	
	if( -e "/var/run/dhcpcd-$interface.pid") {
		system("dhcpcd -k $interface > /dev/null 2>&1");
		system("rm -rf /var/run/dhcpcd-$interface.pid &> /dev/null");
	}
	my $ret = system("ifconfig $interface 0.0.0.0 > /dev/null 2>&1") >> 8;
	if($ret == 0) {
		$ret = system("ifconfig $interface down > /dev/null 2>&1") >> 8;
	}

	return $ret;
}

sub config_static
{
	my ($interface, $ip, $mask) = @_;

	if( -e "/var/run/dhcpcd-$interface.pid") {
		system("dhcpcd -k $interface > /dev/null 2>&1");
		system("rm -rf /var/run/dhcpcd-$interface.pid &> /dev/null");
	}
	my $ret = system("ifconfig $interface $ip netmask $mask > /dev/null 2>&1") >> 8;
	
	if($ret == 0) {
		system("ifconfig $interface up > /dev/null 2>&1");
	}

	return $ret;
}

