#!/usr/bin/perl -w

#use warnings;
#use strict;

use MyLdap;
use CGI qw/:standard/;
use CGI::Carp qw(fatalsToBrowser);

my $SERVER = '157.92.113.2';
my $CAFILE = '/var/www/docs/derecho.uba.ar/ca.crt';
my $BASEDN = "dc=derecho,dc=uba,dc=ar";
my $USERAT = "mail";

print header(-type => "text/html; charset=ISO-8859-1"),
	start_html,
	h1("Formulario de cambio de clave");

if(param("user") && param("oldpw") && param("newpw1") && param("newpw2")) {
	my $ldap = Net::LDAP->new( $SERVER,
		verify => 'require',
		cafile => $CAFILE)
		or die "Error conectando al servidor LDAP: $!\n";
	my $r = MyLdap::login($ldap, $BASEDN, $USERAT, param("user"),
		param("oldpw"));
	if($r == 0) {
		print p(b("Usuario o clave original incorrectos"));
	} elsif($r < 0) {
		print p(b("Error inesperado: $@"));
	} elsif(param("newpw1") ne param("newpw2")) {
		print p(b("Las nuevas claves no coinciden"));
	} else {
		$r = MyLdap::passwd($ldap, $BASEDN, $USERAT, param("user"),
			param("newpw1"));
		if($r != 1) {
			print p(b("Error: $@"));
		} else {
			print p(b("Clave cambiada exitosamente!"));
			param(-name => 'user',-value => '');
		}
	}
	$ldap->unbind();
}

print start_form({ -method => "POST" });

print p("Usuario (email): ",
	input({ -type => "text", -size => 30, -name => 'user',
		-value => param("user") || ""}));
print p("Clave actual: ",
	input({ -type => "password", -size => 20, -name => 'oldpw',
		-value => ""}));
print p("Clave nueva: ",
	input({ -type => "password", -size => 20, -name => 'newpw1',
		-value => ""}));
print p("Clave nueva: ",
	input({ -type => "password", -size => 20, -name => 'newpw2',
		-value => ""}));

print p(input({-type => "submit"}));

print end_form, end_html;
