#!/usr/bin/perl
#  Copyright 2001-2024 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.

# Fix any passwords with trailing CR/LF

my %lex = ('Remove Trailing CR/LF' => 'Remove Trailing CR/LF',
	   'Main' => 'Main',
	   'Eoy' => 'Eoy',
	   'Name' => 'Name',
	   'Student Number' => 'Student Number',
	   'Password' => 'Password',
	   'Error' => 'Error',
	   'Fix' => 'Fix'

	   );


use DBI;
use CGI;

# 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 $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);


# print the HTML head section.
my $title = qq{$lex{Fix} $lex{Password}};

print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">
$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{<h1>$title</h1>\n};
print qq{<h3>$lex{'Remove Trailing CR/LF'}</h3>\n};


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

my $sth = $dbh->prepare("select studnum,lastname, firstname, password from student 
 order by lastname, firstname");
$sth->execute;
if ($DBI::errstr){ print $DBI::errstr; die; }

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

    if ( $password =~ m/\n$/ ) { # we have a problem
	$password =~ s/\n$//; # strip
	print qq{<tr><td>$lastname, $firstname ($studnum)</td><td>$password</td></tr>\n};

	my $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>\n};
print qq{</body></html>\n};
