#!/usr/bin/perl

print "Content-type: text/html\n\n";

require "config.idx";

$long = $ENV{'QUERY_STRING'};

if ($long) {
	@pairs=split(/&/,$long);
	foreach $item(@pairs) {
		($name,$content)=split (/=/,$item,2);
		$content=~tr/+/ /;
		$content=~ s/%(..)/pack("c",hex($1))/ge;
		if ($INPUT{$name}) { $INPUT{$name} = $INPUT{$name}.",".$content; }
		else { $INPUT{$name} = $content; }
	}
}
else {
	read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
	@pairs = split(/&/, $buffer);
	foreach $pair (@pairs) {
		($name, $value) = split(/=/, $pair);
		$value =~ tr/+/ /;
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
		if ($INPUT{$name}) { $INPUT{$name} = $INPUT{$name}.",".$value; }
		else { $INPUT{$name} = $value; }
	}
}




if ($INPUT{action} eq "generate") { &generate; }
else { &main; }




sub generate {





use DBI;
my $dsn = "DBI:mysql:database=$d_name;host=localhost";
my $dbh = DBI->connect($dsn, $d_username, $d_pass, {RaiseError => 1}) || die $DBI::errstr;

my $iasth = $dbh->prepare("select userid,email from users where email = '$INPUT{email}'");
$iasth->execute;

while (($userid,$email) = $iasth->fetchrow_array()) {

@Chars = split '',
'abcdefghijkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789@!';
for (1..($ARGV[0] ||= 1)){
$Password;
for (1..9){
$Password .= $Chars[rand @Chars];
}
#print "$Password\n";
}


my $jasth = $dbh->do("update users set password = PASSWORD('$Password') where userid = '$userid'");


open(MAIL,"|/usr/sbin/sendmail -t");
print MAIL "To: $email\n";
print MAIL "From: account\@munciemls.com\n";
print MAIL "Subject: Your New Password - MuncieMLS.com\n\n";
print MAIL "Per your request, we have generated a new password for you.  Please login using:\n\nEmail:          $email\nPassword:          $Password\n\nPlease change your password once you login to your MyHomes account.\nThank you,\nMuncieMLS.com System\n";
close(MAIL);


&header;
print qq~


		<td valign="top" width="581">
<br><br>
Password sent.



~;


&footer;


exit 0;

}


&header;
print qq~


		<td valign="top" width="581">
<br><br>
That email address doesn't exist in our database.  Please try enter it again.



~;


&footer;


exit 0;



}


sub main {

&header;
print qq~


<td valign="top" width="581">
<br><br>
<font size="4"><b>Generate New Password</b></font><br><br>
<form method=post action=lostpassword.idx>
<input type=hidden name=action value=generate>
Your Email Address: <input type=text name=email size=25 value=$INPUT{Email}><br>
<input type=submit value="E-Mail Password To Me">
</form>



~;


&footer;



}