#!/usr/local/bin/perl

# pg95passwd.pl - David H. Bennett - dave@bensoft.com - Version 1.0
#
# This program will create password entries that can be used by 
# the mod_auth_pg95.c module for the Apache web server.
#
# You can get the latest version from:
#   ftp://ftp.bensoft.com/apache/pg95passwd.pl
#
# Requires:
#   Perl 5
#   Postgres95          
#   Apache web server
#   pg95perl library
#

use Pg;

# --- Edit these values to suit your needs ---

$pghost    = 'localhost';
$pgport    = '5432';
$pgoptions = '';
$pgtty   = '';
$dbname    = 'my_database';

$tablename = 'my_table';
$uidfield = 'login';
$passfield = 'password';

# --- Don't edit below this line ---

# these are from libpq-fe.h

$PGRES_EMPTY_QUERY= 0 ;
$PGRES_COMMAND_OK= 1 ;
$PGRES_TUPLES_OK= 2 ;
$PGRES_COPY_OUT= 3 ;
$PGRES_COPY_IN= 4 ;
$PGRES_BAD_RESPONSE   = 5 ;
$PGRES_NONFATAL_ERROR = 6 ;
$PGRES_FATAL_ERROR= 7 ;

# Calculate salt value for crypt function
#
@saltair= split
  //,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxyz0123456789./";
sub get_salt {
  srand();
  $iOff = int(rand($#saltair));
  $iOff2 = int(rand($#saltair));
  return join("",$saltair[$iOff],$saltair[$iOff2]);
}

sub PGError {
  print "Database Access Error: ", @_;
  exit;
}

# specify the database to access
$conn = PQsetdb ($pghost, $pgport, $pgoptions, $pgtty, $dbname);
&PGError() if PQstatus($conn);

$strUID=$ARGV[0];

if ($strUID eq "") {
  print "Usage: pg95passwd.pl {user name}\n";
  print "\n";
  exit;
}

# Get the password from the user
#

print "Please input the password: ";
$strEnterPass = <STDIN>;
chop $strEnterPass;

print "Re-type the password: ";
$strEnterPass2 = <STDIN>;
chop $strEnterPass2;

if ($strEnterPass ne $strEnterPass2) {
  print "Passwords are not identical!\n";
  exit;
}

# Delete the user record if it exists.
# 
$cmd = "delete from $tablename where $uidfield = '$strUID'";
PQexec($conn, $cmd);

# Encrypt the password entered
# 
$strCryptPass = crypt($strEnterPass,get_salt());

# Insert it into the database
#
$cmd = "insert into $tablename ($uidfield,$passfield) values ('$strUID','$strCryptPass')";
PQexec($conn, $cmd);

print "Password Revised!\n";

PQfinish($conn);
