#!/usr/bin/perl -w
# This script (sophomorix-minitest) is maintained by Rüdiger Beck
# It is Free Software (License GPLv3)
# If you find errors, contact the author
# jeffbeck@web.de  or  jeffbeck@gmx.de

# Dieses Script ist NICHT im Paket sophomorix-developer enthalten



# Bibliotheken
use strict;
use Getopt::Long;
use Sophomorix::SophomorixConfig;
use Sophomorix::SophomorixBase;
use Sophomorix::SophomorixAPI;
use Sophomorix::SophomorixPgLdap;
use Sophomorix::SophomorixTest;
use Test::More "no_plan";
Getopt::Long::Configure ("bundling");

use DBI;
use Crypt::SmbHash;
use Net::LDAP;
use IMAP::Admin;

# login, "": set for all

my $user="blackmri";


# must be uid:encrypted password:unused:
my $pwd_file="/var/log/sophomorix/dist-upgrade/sophomorix_passwords";

print "updating Data in postgres\n";

my $dbh=&db_connect();

#if ($user eq ""){
    open(PWFILE, "<$pwd_file") || die "Fehler: $! $pwd_file" ;
    while (<PWFILE>){
        my ($login,$linux_pass,$lmpassword,
            $ntpassword,$first_pass) = split(/:/);
        if ($user eq "" or $login eq  $user){
	        print "\n";
	        print "Login:           $login\n";
	        print "userpassword:    $linux_pass\n";
	        print "sambalmpassword: $lmpassword\n";
	        print "sambantpassword: $ntpassword\n";
	        print "firstpassword:   $first_pass\n";
                &set_sophomorix_pass_pg($login,$linux_pass,$lmpassword,
                                        $ntpassword,$first_pass);
	}
    }
    close(PWFILE);

# weiter: setzen für ein user


&db_disconnect($dbh);



exit;



############################################################
# sub
############################################################


sub set_sophomorix_pass_pg {
    my ($login,$linux_pass,$lmpassword,$ntpassword,$first_pass) = @_;
    my $sql="SELECT id FROM userdata WHERE uid='$login'";
    my ($id)= $dbh->selectrow_array($sql);
    if (not defined $id){
       print "ERROR: User $login not found in database to set password!\n";
       return;
    }

    # linux
    $sql="UPDATE posix_account SET 
                 userpassword='$linux_pass' 
            WHERE id = $id";
    print "\nSQL: $sql\n";
    $dbh->do($sql);

    # windows
    $sql="UPDATE samba_sam_account 
             SET sambalmpassword='$lmpassword', 
                 sambantpassword='$ntpassword'
           WHERE id = $id";
    print "\nSQL: $sql\n";
    $dbh->do($sql);
}
