#!/usr/bin/perl -wT

################################################################
# @(#) $Id: pw_change.pl,v 1.1 2001/03/24 04:19:58 andr Exp $
# 
# A.Gaponenko, March 2001
#

use Pg;

delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};   # Make %ENV safer
$ENV{'PATH'} = "/bin:/usr/bin";

umask 077;

sub mylog {
#    local $LOG;
#    open(LOG, ">>/tmp/admlog") or die "Can't open log";
#    print LOG scalar(localtime()) . ": @_\n";
    print "\n<br>@_<br>\n";
#    close(LOG);
}

################################################################
# The following information is required:
my @fields = ('user',
	      'pw',
	      'dbname',
	      'pwnew'
	      );

my %input;
foreach my $i (@fields) {
    $input{$i} = undef;
}

# Read data
MAIN:
    while($line = <STDIN>){
	chomp($line);
	last MAIN if($line =~ /^EOF$/);
#	mylog "Read: $line<br>\n";

	if ($line =~ /^([^:]+):(.*)$/) {
	    $input{$1} = $2;
	} else {
	    die mylog("Bad line:\n$line\n");
	}
    }

# Check that all data required were defined.
foreach my $i (@fields) {
    die mylog("Error: undefined $i\n")
	unless defined($input{$i});
}

################################################################
# bail out if the user is a special one

if($input{'user'} eq "e614") {
    die(mylog("Password change for user $input{user} is forbidden.\n"));
}

################################################################
# Check that old password is correct.

$conn = Pg::connectdb("dbname=$input{dbname}"
		      ." user=$input{user} "
		      ." password=$input{pw} "
		      );
die mylog("Can't connect to the database: wrong old password?")
    if($conn->status != PGRES_CONNECTION_OK);

################
## Set new passwd

local $PWPROG;
if(!open(PWPROG, 
	 "|/usr/bin/pg_passwd "
	 ."/var/lib/pgsql/data/passwd "
#test:	 ."/tmp/passwd "
	 .">/dev/null 2>&1"
	 )) 
{
    die mylog("Can't pipe to PWPROG");
}

print PWPROG "$input{user}\n$input{pwnew}\n$input{pwnew}\n"
    and close(PWPROG)
    or  die(mylog("Can't write to PWPROG"));

mylog("Successfully changed password for user $input{user}.");

exit 0;
################################################################
