#!/apps/bin/perl
#
# $Id: edit_task.pl,v 1.5 2006/04/04 19:57:18 marki Exp $
##########################################################################
#   Brief Discription:
#
#   execution:  new_task
#
#   cgi script to add a new maintenance task to the maintenance 
#   scheduler and notifier.
#
#   created:  Fri Apr 17 20:22:24 EDT 1998
#
#   author of the script: arne 
#   
##########################################################################


use Time::CTime;
use Time::JulianDay;
use CGI qw(:all);
use DBI;

for ($i=1; $i<32; $i++) {
    $day_num[$i] = $i;
}
%month_labels = (
		 '0' =>'Jan',
		 '1' =>'Feb',
		 '2' =>'Mar',
		 '3' =>'Apr',
		 '4' =>'May',
		 '5' =>'Jun',
		 '6' =>'Jul',
		 '7' =>'Aug',
		 '8' =>'Sep',
		 '9' =>'Oct',
		 '10' =>'Nov',
		 '11' =>'Dec'
		 );
$cgi_query = new CGI;

print $cgi_query->header();
print $cgi_query->start_html(-title=>'Hall D Maintenance Task Edit Form',
				 -BGCOLOR=>'#bbbbbb');
print $cgi_query->start_form();
				 
$time_format="\%c";
$now = time();
if (param('update')) {
    $password = $cgi_query->param('passwd');
    if ($password ne 'keepitrunning') {
	print $cgi_query->p("The password you entered is incorrect, please try again...");
    } else {

	$task = $cgi_query->param('task_old');   # you should check the task is unique!
	$task_new = $cgi_query->param('task_new');  
	$email1 = $cgi_query->param('email1');
	$email2 = $cgi_query->param('email2');
	$period = $cgi_query->param('period');
	$last_day = $cgi_query->param('last_day');
	$last_month = $cgi_query->param('last_month');
	$last_year = $cgi_query->param('last_year');
	$long_task = $cgi_query->param('long_task');

	$period_type=1;

# convert last maintenance date into seconds since epoch
	$last_maintenance = jd_timelocal(0,0,8, $last_day, $last_month, $last_year);
# convert period into seconds
	$period = $period*86400.;
# calulate next maintenance date
	$next_maintenance = $last_maintenance + $period;

	print $cgi_query->p("task: $task was last performed $last_maintenance and needs to be performed again on $next_maintenance");

# create the SQL query and send it

	$sql_cmd = "UPDATE maintenance SET  ";
	$sql_cmd .= "email1=\'$email1\', email2=\'$email2\', long_task=\'$long_task\',";
	$sql_cmd .= "last_maintenance=$last_maintenance, next_maintenance=$next_maintenance, ";
	$sql_cmd .= "period=$period, period_type=$period_type ";
	$sql_cmd .= "WHERE task=\'$task\' ";

	#print $sql_cmd;

	$database = "maintenance";
	# Changed to localhost 3/4/2014 by M. Wise after switch to halldweb.jlab.org
	# $hostname = "halldweb1.jlab.org";
	$hostname = "localhost";
	$user = "maintainer";
	$password = "";
	$dbh = DBI->connect("DBI:mysql:$database:$hostname", $user, $password);

	do_sql();

	print "$task_new $task <BR>";
	if (($task_new) && ($task_new ne $task)) {
	    $sql_cmd  = " SELECT task FROM maintenance ";
	    $sql_cmd .= " WHERE task = \'$task_new\'";
	    do_sql();
	    if (@column = $sth->fetchrow_array) {
		print "<b>Task name:$task_new not unique...go back and try a different taskname</b><BR>";
	    } else {
		$sql_cmd  = "UPDATE maintenance SET task = \'$task_new\' ";
		$sql_cmd .= "WHERE task = \'$task\'";
		do_sql();
	    }
	}

    }
    # Changed by M. Wise, 3/4/2015 to reflect hostname change (halldweb1 -> halldweb)
	# print "Location: https://halldweb1.jlab.org/cgi-bin/maintenance/cgi/status.pl\n\n";
    print "Location: https://halldweb.jlab.org/cgi-bin/maintenance/cgi/status.pl\n\n";

} else { # give them the form to fill out  FIRST get the old values for this task


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

    $database = "maintenance";
    # Changed 3/4/2014, M. Wise to reflect host name change from halldweb1 to halldweb
	# $hostname = "halldweb1.jlab.org";
    $hostname = "localhost";
    $user = "maintainer";
    $password = "";
    $dbh = DBI->connect("DBI:mysql:$database:$hostname", $user, $password);
    $task = $cgi_query->param('task');
    $task =~ s/\\s/ /g;
    $task =~ s/\\num/#/g;
    $cgi_query->delete_all();
    $task_w_spaces = $task;

    print $cgi_query->hidden('task_old',$task);
    
    $sql_cmd = "SELECT long_task, email1, email2, next_maintenance, last_maintenance, period FROM maintenance WHERE task=\'$task\'";
    do_sql();
    @column = $sth->fetchrow_array;
    $long_task = $column[0];
    $email1 = $column[1];
    $email2 = $column[2];
    $next_maintenance = $column[3];
    $last_maintenance = $column[4];
    $period = $column[5];
    $period = $period/86400.;
    $todays_day  =  strftime('%d',(localtime($last_maintenance)));
    $todays_month=  strftime('%m',(localtime($last_maintenance)))-1;
    $todays_year =  strftime('%Y',(localtime($last_maintenance)));

    print $cgi_query->p("Your are editting the Hall D Maintenance task: <B> $task  <BR> </B> 
click on the Submit button to modify this existing task. ");

    print $cgi_query->p("Change the <B> task name </n>",
			textfield(-name=>'task_new',
				  -size=>20,
				  -maxlength=>40,
				  -default=>$task));
    print $cgi_query->p("Enter the primary EMAIL contact address",
			textfield(-name=>'email1',
				  -size=>20,
				  -maxlength=>40,
				  -default=>$email1));
    print $cgi_query->p("Enter the secondary EMAIL contact address",
			textfield(-name=>'email2',
				  -size=>20,
				  -maxlength=>40,
				  -default=>$email2));
    print $cgi_query->p("How often is the maintenance to be done \(in days\)",
			textfield(-name=>'period',
				  -size=>5,
				  -maxlength=>10,
				  -default=>$period));

    print $cgi_query->p("When was the last maintenance performed?",
			popup_menu(-name=>'last_day',
				   -values=> \@day_num,
				   -default=>$todays_day),
			"-",
			popup_menu(-name=>'last_month',
				   -values => [sort numerically keys(%month_labels)],
				   -default =>$todays_month,
				   -labels  => \%month_labels),
			"-",
			popup_menu(-name=>'last_year',
				   -values=> ['2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022',  '2023', '2024', '2025', '2026', '2027', '2028'],
				   -default=>$todays_year));


    print $cgi_query->p("Enter a concise description of the maintenance task");
    print $cgi_query->textarea(-name=>'long_task',
			       -rows=>20,
			       -columns=>50,
			       -default=>$long_task);
    
    print $cgi_query->p("Enter the Hall D Maintenance password",
			password_field(-name=>'passwd',
				  -size=>20,
				  -maxlength=>40));
    print $cgi_query->p(submit("SUBMIT"), reset("RESET FORM"));
    	$task_nospaces = $task;
	$task_nospaces =~ s/ /\\s/g;
	$task_nospaces =~ s/#/\\num/g;
    print a({href=>"delete_task.pl?task=$task_nospaces"},"Delete task \"$task\"");

}
print $cgi_query->endform;

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;
}
