#!/usr/bin/perl
# start_image mac tmpfile
use POSIX qw(strftime);


require '/usr/lib/kwartz/control/sharelib.pl'; 	 
require 'hostlib.pl'; 	 #load host management library
require 'deploy.pl'; 	 

my $AddrMAC=shift @ARGV;
my $tmpname=shift @ARGV;

my $host=&GetHostByMac($AddrMAC);

if ( ! $host ) {
	print "\@mac $AddrMAC non trouve";
	exit 1;
}
$host = (split '\.', $host)[0];

# recup iuuid 
my $iuuid='';
my $iuuidfile="$deploydir/computers/$host/image.iuuid";
if ( -f $iuuidfile ) {
	open(my $fh, "<", "$iuuidfile");
	if ($fh) {
		$iuuid=<$fh>;
		close($fh);
	}
	chomp $iuuid;
	unlink ($iuuidfile);
} else {
	my $ncount = 0;
	$iuuid=strftime "$host.%Y%m%d", localtime();
	while ( -d "$deploydir/masters/$iuuid" ) {
		$ncount++;
		$iuuid=strftime "$host.%Y%m%d", localtime();
		$iuuid = $iuuid."-$ncount";
	}
}
#warn $iuuid;
# prparation dossier
my $masterdir="$deploydir/masters/$iuuid";
if ( ! -d $masterdir ) {
	mkdir $masterdir, 0755;
}
my @id=`id pulse2`;
if ( $?==0 ) {
	`chown pulse2: $masterdir`;
}
# voir si on purge  (ATTENTION aux fichiers crs via kwartzsysprep)

( -f "$masterdir/reginfo.txt" ) && unlink ("$masterdir/reginfo.txt");

#renvoie iuuid

( -f $tmpname ) || die "Fichier '$tmpname' non trouv\n";
if ( open( TMP, ">$tmpname") ) {
	print TMP "$iuuid\n";
	close TMP;
	exit 0;
}
exit 1;
