#!/usr/bin/perl
# end_restore mac iuuid

use File::Path qw(rmtree);
use MIME::Base64;

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

sub FixNTPasswd {
    my ($host, $NThash) = @_;
    my $dn="uid=$host\$,$computersdn";
    
	system("smbpasswd -a -m $host");
    $replace={      sambaLMPassword=>[],
                    userPassword=>[],
                    sambaNTPassword=>$NThash,
                    sambaPwdLastSet=>time };
    
    warn $dn;
    $result=$ldap->modify($dn , replace=>$replace );
    if ($result->code) {
        warn "Impossible de maj le compte d'ordinateur '$host':", $result->error;
    } else {
        warn "OK";
    }
}

sub FixADPasswd {
    my ($host, $NThash) = @_;

    system("smbpasswd -a -m $host");

    my $res = 1;  # assumes false
    $res = system("pdbedit --user=\"$host\$\" --set-nt-hash=\"$NThash\"");

    if ($res) {
        warn "Impossible de maj le compte d'ordinateur '$host'";
    } else {
        warn "OK";
    }
}

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

my $host=&GetHostByMac($AddrMAC);

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

my $iuuidfile="$deploydir/computers/$host/image.iuuid";
unlink $iuuidfile if (-f $iuuidfile);

# recup iuuid 
my $masterdir="$deploydir/masters/$iuuid";	
if ( -d $masterdir ) {
	if ( -f "$masterdir/reginfo.txt" ) {
	
		my $hashnt=`grep \"^hashnt=\" $masterdir/reginfo.txt | sed -e \'s/hashnt=//\'`; chomp($hashnt);
		exit 0 unless($hashnt);

		my $is_ad_dc=-f '/var/lib/samba/private/sam.ldb';
		if ($is_ad_dc) {
			&FixADPasswd($host, $hashnt);
		} else {
			&FixNTPasswd($host, $hashnt);
		}
	}
} else {
	warn "$masterdir non trouv�\n";
	exit 1;
}
exit 0
