#!/usr/bin/perl -w
use lib "/usr/lib/diskless";
use strict;
use diskless;
use imagedir;
use hostdir;

my $ip="";
my $m=0;

if ($#ARGV >= 0) 
{ 
	if ($ARGV[0] eq "--help")
	{
		print<<EOT;

No help currently available

EOT
		exit 0;
	}
}

my $imagedir;
if ($m <= $#ARGV)
{
	$imagedir=$ARGV[$m]; $m++
}
else
{
	$imagedir = "diskless"->input("Directory of group","/var/lib/diskless/default/root");
}
my $error = undef;
my $theimagedir = "imagedir"->get($imagedir,\$error);
if (!$theimagedir)
{
	die($error->msg."\n");
}

my $ip_on_cmdline = 0;
my @list = ();
while (!$ip_on_cmdline || $m <= $#ARGV)
{
	if ($m <= $#ARGV)
	{
		$ip=$ARGV[$m]; $m++;
		$ip_on_cmdline = 1;
	}
	else
	{
		$ip = "diskless"->input("IP Address of client","stop");
	}
	last if ($ip =~ /[a-zA-Z ]/);

	my %options = ();
	while ($m <= $#ARGV && $ARGV[$m] =~ /^([A-Za-z_0-9]+)=(.*)$/)
	{
		$options{$1}=$2; $m++;
	}

	$error = undef;
	my $host = undef;
	my $thehostdir = "hostdir"->get($theimagedir,$ip,\$error);
	if (defined($error) and $error->id == "error"->notfound)
	{
		$error=undef;
		$thehostdir = "hostdir"->create($theimagedir,$ip,\$error);
		die($error->msg."\n") if (defined($error));
	}
	elsif (defined($error))
	{
		die($error->msg."\n");
	}

	print "\n-------------------------------------\n";
	print "Configure host $ip...\n";
	"diskless"->config($thehostdir,\%options);
	$thehostdir->save(\$error) or die($error->msg."\n");
	print "... host $ip configured.\n";
	print "-------------------------------------\n";

	@list = (@list,$thehostdir);
}

"hostdir"->update_many(\@list,\$error) or die($error->msg."\n");
exit 0;
