#!/usr/bin/perl
#  Copyright 2001-2017 Leslie Richardson

#  This file is part of Open Admin for Schools.

#  Open Admin for Schools is free software; you can redistribute it 
#  and/or modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2 of 
#  the License, or (at your option) any later version.

my %lex = ('Update' => 'Update',
	   'Main' => 'Main',
	   'Eoy' => 'Eoy',
	   'Name' => 'Name',
	   'Student Number' => 'Student Number',
	   'Password' => 'Password',
	   'Error' => 'Error',
	   );


# Password config; rest in admin.conf
$g_studentpwd_minfreq = .001;
$g_studentpwd_avgfreq = .001;
$g_studentpwd_lang = 'en'; # only en or de available.

# For Checking
my $g_studentpwd_groups = 0; # turn off character group (uppercase, lowercase, symbols) checking
my $g_studentpwd_following = 0; # turn off following character checking (keyboard, same)
my $maxuidnumber = 10000; # just in case nothing yet in system.


use CGI;
use DBI;
use Data::Password qw(:all);  # for password checking...
use Crypt::GeneratePassword qw(:all); # password generation.


# Read config variables
eval require "../../etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}



my $q = new CGI;
print $q->header( -charset, $charset ); 
my %arr = $q->Vars;


my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);


# print the HTML head section.
print qq{$doctype\n<html><head><title>$lex{Update} $lex{Password}</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{$chartype\n</head><body>\n};
print qq{[ <a href="$homepage">$lex{Main}</a> | \n};
print qq{<a href="$eoypage">$lex{Eoy}</a> ]\n};

print qq{<table cellpadding="3" cellspacing="0" border="1" style="margin:1em;">\n};
print qq{<tr><th>$lex{Name} ($lex{'Student Number'})</th><th>$lex{Password}</th>\n};

# my $sth = $dbh->prepare("select studnum,lastname, firstname from student");
my $sth = $dbh->prepare("select studnum,lastname, firstname from student
			where password is null or password = ''");

$sth->execute;
if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

while ( my ($studnum, $lastname, $firstname) = $sth->fetchrow ) {

    my $password = word( $g_studentpwd_minlen, $g_studentpwd_maxlen,
			 $g_studentpwd_lang, $g_studentpwd_signs,
			 $g_studentpwd_caps, $g_studentpwd_minfreq,
			 $g_studentpwd_avgfreq );

    # my $password = `/usr/local/bin/apg -n1 -m6 -x7 -M CLN -E lI`;
    # Note: -M characters, letters,numbers exclude 'ell' and capital 'eye'
    # $password =~ s/\n$//; # strip trailing CR/LF

    print qq{<tr><td>$lastname, $firstname ($studnum)</td><td>$password</td></tr>\n};

    $sth1 = $dbh->prepare("update student set password = ? where studnum = ?");
    $sth1->execute( $password, $studnum );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
  
}

print qq{</table></body></html>\n};
