#!/apps/bin/perl

# ################################################################# 
# Krister Bruhwel
# May 2010
#
# Addition to Arne's maint program to delete records from the DB
#
# ################################################################# 


use CGI qw(:all);
use DBI;

$cgi_query = new CGI;

print $cgi_query->header();
print $cgi_query->start_html(-title=>'Hall D Maintenance Task Delete Form', -BGCOLOR=>'#bbbbbb');

if (param('update')) {

	$password  = $cgi_query->param('passwd');
	$delRecord = $cgi_query->param('Delete Record');
	$task = $cgi_query->param('task');

    	if ($password ne 'keepitrunning') {
		print $cgi_query->p("The password you entered is incorrect, please try again ...");
	}   
	elsif($delRecord ne 'on'){
		print $cgi_query->p("You must check the delete box ...");
	}
	else{
		$database = "maintenance";
		# Changed to localhost bby M. Wise, 3/4/2015 after switch to halldweb
		# $hostname = "halldweb1.jlab.org";
		$hostname = "localhost";
		$user = "maintainer";
		$password = "";
		$dbh = DBI->connect("DBI:mysql:$database:$hostname", $user, $password);


		$task =~ s/\\s/ /g;
		$task =~ s/\\num/#/g;

		$sql_cmd = "delete from $database where task='$task'";

		do_sql();
		print $cgi_query->p("Task \"$task\" has been deleted.");
		# Changed to reflect new hostname (halldweb vs halldweb1) by M. Wise, 3/4/2015
    		#print a({href=>"https://halldweb1.jlab.org/cgi-bin/maintenance/cgi/status.pl"},"Back to Status Page");
    		print a({href=>"https://halldweb.jlab.org/cgi-bin/maintenance/cgi/status.pl"},"Back to Status Page");
	} 
 }
elsif (param(task)) {

	
	print $cgi_query->start_form();
					 
	$task = $cgi_query->param('task');
	$task =~ s/\\s/ /g;
	$task =~ s/\\num/#/g;
	$task_w_spaces = $task;
	$task_nospaces = $task;
	$task_nospaces =~ s/ /\\s/g;
	$task_nospaces =~ s/#/\\num/g;
	$cgi_query->delete_all();

	    
    	print $cgi_query->hidden('update','yes');
    	print $cgi_query->hidden('task', $task_nospaces);

	print "<TABLE BORDER=1><TR><TD BGCOLOR=#F78181>";
	print $cgi_query->p("Delete task \<font color=yellow\>\"$task_w_spaces\</\font\>\"");
	print "</TD></TR><TR><TD BGCOLOR=lightgray>";
	print $cgi_query->checkbox(-name=>'Delete Record');
        print $cgi_query->p("Password",
			password_field(-name=>'passwd',
				  -size=>20,
				  -maxlength=>40));
	print "</TD></TR><TR><TD BGCOLOR=#F78181 ALIGN=center>";
        print $cgi_query->p(submit("SUBMIT"));
	print "</TD></TR></TABLE>";
        print $cgi_query->endform;
}
else{
	print "HI";
}

	sub numerically { $a >= $b; }

sub do_sql {
    $sth = $dbh -> prepare($sql_cmd)
        or die "Can't prepare $sql_cmd: $dbh->errstr\n";
    $rv = $sth -> execute
        or die "Can't execute the query $sql\n error: $sth->errstr\n";
    return;
}
