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

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 $server_addr = ip_to_int($ARGV[2]);
my $client_subnet = ip_to_int($ARGV[3]);

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

    
sub ip_to_int
{
	my @octs = ($_[0] =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/);
	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);
	}

	$client_mac =~ s/:-//g;
	$query = "INSERT INTO static_clients (client_addr, client_hw_addr, client_subnet, server_addr, end_lease) 
					VALUES('$client_ip', '$client_mac', $client_subnet, $server_addr, NULL)";
	print "QUERY: $query\n";

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

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

