#!/usr/bin/perl
# Argument: AdresseIp AdresseMac Droit
# Auteur Secret Olivier

use strict;
use warnings;

require '/usr/lib/kwartz/control/sharelib.pl';
require '/usr/lib/kwartz/control/hostlib.pl';
require '/usr/lib/kwartz/control/deploy.pl';


if ($#ARGV != 2)
{
    die "Usage : $0 AdresseIp AdresseMac query\n";
}

### Variable
my $ip = "$ARGV[0]";
my $mac = "$ARGV[1]";
my $query = "$ARGV[2]";
my $hostname;
my $know = "true";
my $images = "";
my $options = "";
my $menu = "";
my $action = "";
my $i = 0;

our $deploydir;
our %hostlist;
our %domainlist;

sub uniq { my %seen; grep !$seen{$_}++, @_ }

sub GetImages {
	my ($hn) = @_;

	my %images=map {chomp; $3=>$2 if (/^([^:]+):([^:]+):([^:]+)/)} `ls-image.pulse`;
	my $opts;
	my @imgs;
	my @opts;
	
	my $imgs = $hostlist{$hn}{'bootimage'};
	if ($imgs eq ' ') {
		$imgs = $domainlist{$hostlist{$hn}{'subdomain'}}{'bootimage'};
	}
	
	return ('','') if ($imgs !~ m/pulse_op/);

	my @imglist = split(' ', $imgs);

	foreach my $img (@imglist) {
		next if ($img =~ m/local_pulse/);
        if ($img =~ m/_op$/ || $img =~ m/no-delay/) {
			push @opts, $img;
		} else {
			push @imgs, $img if grep {$_ eq $img} keys(%images);
		}
    }

    if ( -f "/home/kwartz/deploy/pulse.opts" ) {
		my @pulseopts = `cat /home/kwartz/deploy/pulse.opts`;
		foreach (@pulseopts) {
			if (m/^\s*Options sshfs/) {
				push @opts, "sshfs_op";
			}
		}
    }
    my @uniq_opts = uniq(@opts);
    
    $imgs = join(' ', @imgs);
    $opts = join(' ', @uniq_opts);
    
    
	return ($imgs, $opts);
}

sub GetImagesRembo {
	my ($hn) = @_;

	my %images=map {chomp; $3=>$2 if (/^([^:]+):([^:]+):([^:]+)/)} `ls-image`;
	my $opts;
	my @imgs;
	my @opts;
	
	my $imgs = $hostlist{$hn}{'bootimage'};
	if ($imgs eq ' ') {
		$imgs = $domainlist{$hostlist{$hn}{'subdomain'}}{'bootimage'};
	}
	
	my @imglist = split(' ', $imgs);

	foreach my $img (@imglist) {
		if ($img =~ m/local_option/) {
            push @imgs, "local_option";
        } elsif ($img =~ m/_op/ || $img =~ m/no-delay/) {
			push @opts, $img;
		} else {
			push @imgs, $img if grep {$_ eq $img} keys(%images);
		}
    }
    $imgs = join(' ', @imgs);
    $opts = join(' ', @opts);
	return ($imgs, $opts);
}

### Main

# Verification des arguments
if (length($ip) < 7)
{
    die "Erreur argument $ip too small";
}
if (length($mac) != 17)
{
    die "Erreur argument $mac non valide";
}


if ($query =~ m/rembo:(\S+)/) {
	my $authentified = $1;
	my $host;
	
	# Recherche du hostname
	if (!defined($hostname=&GetHostByMac($mac))) {
	    $action = "unknownPost";
	} else {
		$host = (split '\.', $hostname)[0];
	}
    # Test creation image a distance
    if ($action eq "") {
        if (-f "$deploydir/computers/$host/image.iuuid") {
            $action = "action=create";
        }
    }
    if ($action eq "") {
	    ($images,$options) = &GetImagesRembo($hostname);
		if ("$authentified" eq "true") {
			$menu = "Reboot Creation_Image Effacement_Disque";
		} else {	# $authentified eq false
			$menu = "Reboot";
		}
		$action = "images=\"$images\"\noptimgs=\"$options\"\nmenu=\"$menu\"";
	}
} elsif ($query =~ m/get:(\S+)/) {
	my $authentified = $1;
	my $host;
	
	# Recherche du hostname
	if (!defined($hostname=&GetHostByMac($mac))) {
	    $action = "unknownPost";
	} else {
		$host = (split '\.', $hostname)[0];
	}
    # Test creation image a distance
    if ($action eq "") {
    	($images,$options) = &GetImages($hostname);
        if (-f "$deploydir/computers/$host/image.iuuid") {
            $action = "action=create\noptimgs=\"$options\"";
        } elsif ("$authentified" eq "true") {		
			$menu = "Reboot Creation_Image";
			$action = "images=\"$images\"\noptimgs=\"$options\"\nmenu=\"$menu\"";
		} else {	# $authentified eq false
	        ($images,$options) = &GetImages($hostname);
			$menu = "Reboot";
			$action = "images=\"$images\"\noptimgs=\"$options\"\nmenu=\"$menu\"";
		}
	}
} elsif ($query =~ m/create:(\S+)/) {
	my $imgname = $1;
	
	$action = "";
	
	my $scheduled = ImageScheduled($imgname);
	if ( -d  sprintf("/home/kwartz/rembo/global/hdimages/winnt/%s.img", $imgname )) {
		$action = sprintf(gettext("Une image rembo '%s' existe déjà"), $imgname);
	} elsif (ImageExists($imgname)) {
		# Test si image pulse du meme nom
		$action = sprintf(gettext("L'image pulse '%s' existe déjà"), $imgname);
	} elsif (defined($scheduled)) {
		# Test si une demande de création d'image du même nom a été enregistrée
		$action = sprintf(gettext("L'image pulse '%s' est configurée pour être créée sur le poste '%s'"), $imgname, $scheduled);
	} else {
		my $host=&GetHostByMac($mac);
		if ( $host ) {
			$host = (split '\.', $host)[0];
			my $iuuidfile="$deploydir/computers/$host/image.iuuid";
			# echo -n pour pas le \n de fin
			system("echo -n $imgname > $iuuidfile");
		}
	}

	$action .= "\n";
	
}

print STDERR "action=$action\n";

print "$action";

exit 0;
