#!/usr/bin/perl
# ARG mac operation status info

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

my $AddrMAC=shift @ARGV;
my $operation=shift @ARGV;
my $status=shift @ARGV;
my $info=join(" ", @ARGV);

my $host=&GetHostByMac($AddrMAC);
my $AddrIP = "$hostlist{$host}{'ipaddress'}";
my $duration = "00:00:00";
my $image = "image";

my $logfile = '/var/log/deploy/restore.log';


sub DiffTimestamp {
    my ($start_timestamp, $end_timestamp) = @_;
    my ($start_hour, $start_minute, $start_second) = split(':', $start_timestamp);
    my ($end_hour, $end_minute, $end_second) = split(':', $end_timestamp);

    my $diff_second = $end_second - $start_second;
    if ($diff_second < 0) {
        $diff_second += 60;
        $end_minute -= 1;
    }
    my $diff_minute = $end_minute - $start_minute;
    if ($diff_minute < 0) {
        $diff_minute += 60;
        $end_hour -= 1;
    }
    my $diff_hour = $end_hour - $start_hour;
    if ($diff_hour < 0) {
        $diff_hour += 24;
    }

    my $diff_timestamp = sprintf("%02d:%02d:%02d", $diff_hour, $diff_minute, $diff_second);
    return $diff_timestamp;
}

if ($operation ne 'restoration') {
    exit 0
}

if ($status eq 'start') {
    $image = $info;
    $info = '';
}

if ($status ne 'start') {
    my $start_time = 0;

    # Parse logfile pour rcuperer l'heure de dbut de restauration et le nom de l'image
    open($fh,'<',$logfile) or die("open: $!");
    while (my $line = <$fh>) {
        my ($line_timestamp, $line_AddrMAC, $line_image, $line_status) = (split(',', $line))[0, 1, 4, 6];
        if ($line_AddrMAC eq $AddrMAC && $line_status eq 'start') {
            $start_time = $line_timestamp;
            $image = $line_image;
        }
    }
    close $fh;

    $start_time = (split(' ', $start_time))[1];
    $duration = DiffTimestamp($start_time, `date +'%T'`);
}

system("echo \"`date +'%F %T'`,$AddrMAC,$AddrIP,$host,$image,$operation,$status,$duration,\"'\"$info\"'\"\" >>$logfile");
# system("echo \"`date +'%F %T'`,$AddrMAC,$AddrIP,$host,$image,$operation,$status,$duration,$info\" >>$logfile");
exit 0;
