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

use strict;
use Socket;
use DBI;

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

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;
}

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

my $client_ip = $ARGV[0];
my $server_addr = ip_to_int($ARGV[1]);
my $client_subnet = ip_to_int($ARGV[2]);
my ($query, $sth, $rv, $ref, $ip, $inp, $outp);

#Start
	my $db = DBI->connect("dbi:Pg:dbname=$dbname",$user,"",
				{PrintError => 0});

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

	$query = "INSERT INTO dynamic_clients 
				(server_addr, client_subnet, client_addr, end_lease) 
				VALUES	($server_addr, $client_subnet, '$client_ip', 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

