#!/usr/bin/perl -w

use CGI;
use DBI;
use strict;
unshift(@INC, '.');
use ipac_cfg;

my $q = new CGI;
my $title = "Change passwords";
my $path="https://" . $q->server_name();
my $cgi=$path . "/cgi-bin";
my $cust_id = "0";
my $dbh;
my $pwd_name;
my $sth;
my @row; 
my $user = $ENV{REMOTE_USER};

if ($ENV{HTTPS} ne "on" || $user eq "") {
        print $q->header(-type=>"text/html;", -status=>'403 Forbidden'),
                $q->start_html('Forbidden'),
	        $q->h1('You dont have permission to access this script'),
    	        $q->end_html;
		exit;
}

$dbh = DBI->connect("dbi:Pg:dbname=$ipac_cfg::pg_dbname",
	                        $ipac_cfg::pg_login, $ipac_cfg::pg_pwd,
	                                 { RaiseError => 1, AutoCommit => 0 });

$cust_id = $q->param('cust');
my $pwd_id = $q->param('pass');
if (!defined($pwd_id)) { $pwd_id = ""; }
if (!defined($cust_id)) { $cust_id = ""; }

if (defined($q->param('new_pass1')) && !length($q->param('new_pass1'))) {
	$sth = $dbh->prepare("select crypt from pwds_names where pwd_id=?");
	$sth->execute($pwd_id) or die $sth->errstr;
	@row = $sth->fetchrow_array;
	my $crypt=$row[0];
	$sth = $dbh->prepare("select pwd from pwds where pwd_id=? and cust_id=?");
	$sth->execute($pwd_id, $cust_id) or die $sth->errstr;
	@row = $sth->fetchrow_array;
	my $old_pass = $row[0];
	if($user ne "admin" && check_passwd($q->param('old_pass'), $crypt, $old_pass)) {
	        print $q->header(-type=>"text/html;", 
					    -status=>'403 Forbidden'),
        		$q->start_html('Forbidden'),
        		$q->h2('Password incorrect, please try again or go away'),
        		$q->end_html;
		$dbh->disconnect  or warn $dbh->errstr;
		exit;
	}
	if ($q->param('new_pass1') ne $q->param('new_pass2')) {
	        print $q->header(-type=>"text/html;", 
					    -status=>'403 Forbidden'),
        		$q->start_html('Forbidden'),
        		$q->h2('Passwords mismatch, please try again or go away'),
        		$q->end_html;
		$dbh->disconnect  or warn $dbh->errstr;
		exit;
	}
	my $new_pwd = $q->param('new_pass1');
	$new_pwd = make_passwd($new_pwd, $crypt);
	$dbh->do(q{update pwds set pwd=? where cust_id=? and pwd_id=?},
			undef, $new_pwd, $cust_id, $pwd_id)
                                        or die $dbh->errstr;
	$sth->finish;
	$dbh->commit;
	$dbh->disconnect or warn $dbh->errstr;
	reconfig("pwd_change");
	print "Location: $cgi/ch_pass?cust=$cust_id\n\n" ;
	exit;
}

if (!defined($pwd_id) || !length($pwd_id)) {
	$sth = $dbh->prepare("select pwd_name from pwds_names where pwd_id=?");
	$sth->execute($pwd_id);
	@row = $sth->fetchrow_array;
	$pwd_name = $row[0];
}

if ($cust_id ne "" || $user ne "admin") {
	if ($cust_id eq "") {
		$sth = $dbh->prepare("select cust_id from customers where login=?");
		$sth->execute($user) or die $sth->errstr;
		@row = $sth->fetchrow_array;
		$cust_id=$row[0];
	}
	$sth = $dbh->prepare("select login from customers where cust_id=?");
	$sth->execute($cust_id) or die $sth->errstr;
	@row = $sth->fetchrow_array;
	if ($user eq "admin") {
		$title = "Change password for user '$row[0]' by admin";
	} else {
		if ($user ne $row[0]) {
		        print $q->header(-type=>"text/html;", 
						    -status=>'403 Forbidden'),
        			$q->start_html('Forbidden'),
        			$q->h1('You dont have permission to access this script'),
        			$q->end_html;
			exit;
		}
		$title = "Change password for user '$row[0]'";
	}
}

print  $q->header,
       $q->start_html(-title=>$title);

print "<STYLE type=\"text/css\"><!-- a.noneline {text-decoration: none;} --></style>";

if ($user eq "admin") {
    print "<table><tr><td>".
	    "<IMG BORDER=0 ALT=\"ipac-ng logo\"".
    	    "SRC=\"$path/poweredby.png\"></td><td>".
            "<center><font color=\"#ff0000\" size=6>ipac-ng $title</font></center>".
            "</td></tr></table><A HREF=\"http://sf.net/projects/ipac-ng\">".
		        "ipac-ng home page</A>&nbsp;&nbsp;";
    print "<A HREF=\"$path/stat\">Go to main page</A>&nbsp;&nbsp;";
    print $ipac_cfg::menu;
}

if (!length($pwd_id)) {
##if ($pwd_id eq "") {
	$sth = $dbh->prepare("select pwds.pwd_id, pwd_name from pwds, pwds_names".
			    " where cust_id=? and pwds.pwd_id=pwds_names.pwd_id");
	$sth->execute($cust_id) or die $sth->errstr;
	while (@row = $sth->fetchrow_array) {
		print "<div>Change password for <a href=\"$cgi/ch_pass?cust=$cust_id&pass=$row[0]\"> $row[1] </a></div>";
	}
	$sth->finish;
	$dbh->disconnect  or warn $dbh->errstr;
	exit;
}

if ($user ne "admin") { ## verify password
	print $q->startform,
		"<table><tr>", 
		"<td>Old password for $pwd_name: </td><td>",
		$q->password_field('old_pass'), "</td></tr><tr>", 
		"<td>New password : </td><td>",
		$q->password_field('new_pass1'), "</td></tr><tr>",
		"<td>Retype new password :</td><td>",
		$q->password_field('new_pass2'), "</td></tr></table>",
		$q->hidden('cust', "$cust_id"),
		$q->hidden('pass', "$pwd_id"),
                $q->submit,
                $q->endform;
} else {
	print $q->startform,
		"<table><tr>", 
		"<td>New password : </td><td>",
		$q->password_field('new_pass1'), "</td></tr><tr>",
		"<td>Retype new password :</td><td>",
		$q->password_field('new_pass2'), "</td></tr></table>",
		$q->hidden('cust', "$cust_id"),
		$q->hidden('pass', "$pwd_id"),
                $q->submit,
                $q->endform;
}


if ($q->param('new_pass1') eq "") {
        print $q->end_html;
	$sth->finish;
        $dbh->disconnect or warn $dbh->errstr;
        exit;                                 
}                                             

$dbh->disconnect  or warn $dbh->errstr;
print $q->end_html;
