#!/usr/bin/perl -w
#Script for adding DHCP client into PostgreSQL database
#Writen by Chebotarev Roman (09.11.2008)

use strict;
use Socket;
use DBI;

if( scalar(@ARGV) < 4)
{
    print "Usage: $0 Cient-IP MAC-address Server-IP Client-Subnet\n";
    exit;
}

my $db_name = 'dhcp';
my $user = 'radius';
my $password = '';

my $client_ip = $ARGV[0];
my $client_mac = lc($ARGV[1]);
my $interface_id = ip_to_int($ARGV[2]);
my $int_subnet = ip_to_int($ARGV[3]);

my ($query, $sth, $rv, $ref, $ip, $inp, $outp); 

    
sub ip_to_int
{
	my @octs = split(/\./, $_[0]);
	my $int_id = $octs[0] << 24;
	$int_id += $octs[1] << 16;
	$int_id += $octs[2] << 8;
	$int_id += $octs[3];
	return $int_id;
}
#Start
	my $db = DBI->connect("dbi:Pg:dbname=$db_name",$user,"",
				{PrintError => 0});

	if (defined($DBI::err)) 
	{
		print $DBI::errstr."\n";
		exit($DBI::err);
	}

	$query = "INSERT INTO dhcp_reply (interface_id, client_mac, attribute, value, start_lease, int_subnet) 
				values($interface_id, '$client_mac', 'You-Address', '$client_ip', null, $int_subnet);";
	print "QUERY: $query\n";
	$sth = $db->prepare($query);
	$rv = $sth->execute();
	if (!defined $rv) 
	{
		print "ERROR executing query '$query' : " . $db->errstr . "\n";
		last;
	} else {print "OK\n";}

	$query = "INSERT INTO dhcp_reply (interface_id, client_mac, attribute, value, start_lease, int_subnet) 
			values($interface_id, '$client_mac', 'Client-MAC', '$client_mac', null, $int_subnet);";
	print "QUERY: $query\n";

	$sth = $db->prepare($query);
	$rv = $sth->execute();
	if (!defined $rv) 
	{
		print "ERROR executing query '$query' : " . $db->errstr . "\n";
		last;
	}else {print "OK\n";}

	$sth->finish();
	#Disconnect from DB
	$db->disconnect();
#End

