<?php
include 'ipp.php';
include 'site.php';

$ID = checkID();

// require an explicit project
if (! $ID['proj']) { projectform ($ID); }

//$db = dbconnect($ID['proj']);
$czardb = dbconnect("czardb"); // HACK to connect to czarDb 
$lastUpdateTime = getLastUpdateTime($czardb);

$gpc1db = dbconnect($ID['proj']);


$PATH = getenv("PATH");
putenv("PATH=$BINDIR:$PATH");

$LD_LIBRARY_PATH = getenv("LD_LIBRARY_PATH");
putenv("LD_LIBRARY_PATH=$LIBDIR:$LD_LIBRARY_PATH");


if ($ID['menu']) {$myMenu = $ID['menu'];}
else {$myMenu = "ipp.imfiles.dat";}

menu($myMenu, 'Czartool on '.$lastUpdateTime, 'ipp.css', $ID['link'], $ID['proj']);

$stages=array(
        "processed",
        "loaded_to_datastore",
        "loaded_to_ODM",
        "merge_worthy",
        "deleted_datastore",
        "deleted_dxlayer",
        "merged",
        "deleted_local");

$pass = $ID['pass'];
$proj = $ID['proj'];
$menu = $ID['menu'];

$selectedStage = $_GET[stage];
$selectedLabel = $_GET[label];
$selectedServer = $_GET[server];
$selectedRevertStage = $_GET[revertstage];
$selectedRevertMode = $_GET[revertmode];
$plotType = $_GET[plottype];
$serverCmd = $_GET[servercmd];
$allServerCmd = $_GET[allservercmd];

$headerColor = "#0080c0";
$columnHeaderColor = "lavender";

$labels = getLabels($czardb);

# if no label is selected, use first one in the list
if ($selectedLabel == "") { 
    
    if (sizeof($labels) > 0) $selectedLabel = $labels[0]; 
    else $selectedLabel = "no labels";
}
if ($selectedStage == "") { $selectedStage = "all_stages"; }
if ($plotType == "") { $plotType = "linear"; }

// deal with reverts: turn on or off if requested and pass current revert state for this stage onto labels table later
if ($selectedRevertStage && $selectedRevertMode) turnRevertsOnOff($czardb, $selectedRevertStage, $selectedRevertMode);

// tell selected server to stop or run
if ($selectedServer && $serverCmd) serverStopRun($czardb, $selectedServer,  $serverCmd);

// tell all servers to stop or run
if ($allServerCmd) {

    foreach ($servers as &$server) serverStopRun($czardb, $server,  $allServerCmd);
}


$debug = 0;
$table = "<table bgcolor=\"#FFFFFF\" width=\"700\" align=\"middle\" border=\"1\" cellspacing=\"0\" cellpadding=\"4\" style=\"font-size:80%\">\n";


if ($debug) {
    echo "prog returned $status, and output:<br>";
    for ($i = 0; $i < count($distLabels); $i++) {
        echo "$distLabels[$i]<br>";
    }
}

$isUpdate = ($selectedMode == "update");

// set up the form
echo "<form action=\"czartool_ipptopsps.php\" method=\"POST\">\n";

echo "<input type=\"hidden\" name=\"pass\" value=\"$pass\">\n";
echo "<input type=\"hidden\" name=\"proj\" value=\"$proj\">\n";
echo "<input type=\"hidden\" name=\"menu\" value=\"$menu\">\n";
echo "</form>\n";

echo "<table border=\"0\">";

echo "<tr>";
echo "<td colspan=\"3\" style=\"background-color:#0080c0;\">";
echo "<h1 align=\"middle\">Czartool</h1>";
echo "<h4 align=\"middle\">IPP to PSPS Monitoring</h4>";
echo "</td>";
echo "</tr>";

echo "<tr valign=\"top\">";
echo "<td style=width:100px;text-align:top;\">";
 # time series plot
echo "<br>";
 echo "<img src=\"czartool_getplot.php?mode=$selectedMode&type=t&label=$selectedLabel&stage=$selectedStage&plottype=$plotType\"><br>";
 # rate time series plot
echo "<br>";
 echo "<img src=\"czartool_getplot.php?mode=$selectedMode&type=rt&label=$selectedLabel&stage=$selectedStage&plottype=linear\"><br>";
echo "</td>";
echo "<td style=height:200px;width:10px;text-align:top;\">";
echo "<td style=height:200px;width:400px;text-align:top;\">";

#echo "<br>";

// status table at top
$plotTypeLink = ($plotType == "linear") ? "log" : "linear";
$link = "czartool_ipptopsps.php?pass=" . $pass . "&proj=" . $proj . "&label=" . $selectedLabel . "&stage=" . $selectedStage . "&revertstage=" . $stage . "&plottype=$plotTypeLink";
echo "<br>";
echo $table;
createTableTitle("Status and links", 3);
echo "<tr>\n";
echo "<tr><td>Time of last update</td><td>$lastUpdateTime</td></tr>";
echo "<tr><td>Documentation</td><td><a href=\"http://ps1wiki.ifa.hawaii.edu/trac/wiki/PsPs\"><font color=\"blue\">here</font></a></td></tr>";

echo "</table>\n";

$plotTypeLink = ($plotType == "linear") ? "log" : "linear";
$link = "czartool_ipptopsps.php?pass=" . $pass . "&proj=" . $proj . "&mode=" . $selectedMode . "&label=" . $selectedLabel . "&stage=" . $selectedStage . "&revertstage=" . $stage . "&plottype=$plotTypeLink";



echo "<br>";

       createLabelsTable($pass, 
         $proj, 
         $czardb, 
         $selectedMode, 
         $labels, 
         $distLabels, 
         $pubLabels, 
         $stages, 
         "new", 
         $selectedLabel, 
         $selectedStage, 
         $plotType);

echo "<br>";

echo "</table>";

menu_end();

###########################################################################
#
# Gets labels in use over the last 24 hours
#
###########################################################################
function getLabels($db) {

    # order by descending priority as set in gpc1 database
    $sql = "SELECT DISTINCT label FROM processed WHERE  timestamp >= now() - INTERVAL 1 DAY ORDER BY label";
    if ($debug) {echo "$sql<br>";}

    $qry = $db->query($sql);
    if (dberror($qry)) {echo "<b>error with $sql </b><br>\n";}
    while ($qry->fetchInto($row)) {

        $labels[] = $row[0];
    }

    return $labels;
}

###########################################################################
#
# Creates table for all labels showing all stages for given 'state'
#
###########################################################################
function createLabelsTable(
        $pass, 
        $proj, 
        $db, 
        $selectedMode, 
        $labels, 
        $distLabels, 
        $pubLabels, 
        $stages, 
        $selectedState, 
        $selectedLabel, $selectedStage, $plotType) {

    $isUpdate = ($selectedMode == "update");
    global $headerColor;
    global $columnHeaderColor;

    // setup table
    global $table;
    echo $table;
    createTableTitle("Label status", 13);

    echo "<tr>\n";
    $link = "czartool_ipptopsps.php?pass=".$pass
        ."&proj=".$proj
        ."&mode=".$selectedMode
        ."&label=".$selectedLabel
        ."&stage=all_stages"
        ."&plottype=".$plotType;
    createFormattedTableCell(($selectedStage != "all_stages"), $link, "All stages", 0, "$columnHeaderColor");

    #echo "<th>Label (in order of priority)</th>";
    foreach ($stages as &$stage) {

        if ($stage == $selectedStage) $showLink = 0;
        else $showLink = 1;
        $link = 
            "czartool_ipptopsps.php?pass=".$pass
            ."&proj=".$proj 
            ."&mode=" .$selectedMode
            ."&label=".$selectedLabel
            ."&stage=".$stage
            ."&plottype=".$plotType;

        createFormattedTableCell($showLink, $link, $stage, 0, "$columnHeaderColor");
#        createTableColumnHeader("Dates");
    }

    // setup default link
    $defaultlink = 
        "czartool_ipptopsps.php?pass=".$pass
        ."&proj=".$proj
        ."&mode=" .$selectedMode
        ."&label=".$selectedLabel
        ."&stage=".$selectedStage
        ."&plottype=".$plotType;

    $searchState = "new";
    if ($selectedMode == "update") $searchState = "update";

    // write rows
    foreach ($labels as &$thisLabel) {


        $distributing = false;
        $publishing = false;

        // show distribution/publishing status
        echo "<tr>\n";

        // create link to label summary page for each label
        if ($thisLabel == $selectedLabel) $showLink = 0;
        else $showLink = 1;
        $link = 
            "czartool_ipptopsps.php?pass=".$pass
            ."&proj=".$proj
            ."&mode=" .$selectedMode
            ."&label=".$thisLabel
            ."&stage=".$selectedStage
            ."&plottype=".$plotType;
        createFormattedTableCell($showLink, $link, $thisLabel, 0, null);

        $str = "";
        $anyFaults = false; 

        $link = $defaultlink;
        getStateAndFaults($db, $thisLabel, $selectedState, "processed", $str, $anyFaults);
        createFormattedTableCell(0, $link, $str, $anyFaults, 0);

        getStateAndFaults($db, $thisLabel, $selectedState, "loaded_to_datastore", $str, $anyFaults);
        createFormattedTableCell(0, $link, $str, $anyFaults, 0);

        getStateAndFaults($db, $thisLabel, $selectedState, "loaded_to_ODM", $str, $anyFaults);
        createFormattedTableCell(0, $link, $str, $anyFaults, 0);

        getStateAndFaults($db, $thisLabel, $selectedState, "merge_worthy", $str, $anyFaults);
        createFormattedTableCell(0, $link, $str, $anyFaults, 0);

        getStateAndFaults($db, $thisLabel, $selectedState, "deleted_datastore", $str, $anyFaults);
        createFormattedTableCell(0, $link, $str, $anyFaults, 0);

        getStateAndFaults($db, $thisLabel, $selectedState, "deleted_dxlayer", $str, $anyFaults);
        createFormattedTableCell(0, $link, $str, $anyFaults, 0);

        getStateAndFaults($db, $thisLabel, $selectedState, "merged", $str, $anyFaults);
        createFormattedTableCell(0, $link, $str, $anyFaults, 0);

        getStateAndFaults($db, $thisLabel, $selectedState, "deleted_local", $str, $anyFaults);
        createFormattedTableCell(0, $link, $str, $anyFaults, 0);

        echo "</tr>\n";
    }

    echo "<tr>\n";
    $link = "czartool_ipptopsps.php?pass=" . $pass . "&proj=" . $proj . "&mode=" . $selectedMode . "&label=all&stage=".$selectedStage."&plottype=".$plotType;

    echo "</tr>\n";
    if ($selectedLabel == "all") $showLink = 0;
    else  $showLink = 1;
    $link = "czartool_ipptopsps.php?pass=".$pass."&proj=".$proj."&mode=".$selectedMode."&label=all&stage=".$selectedStage."&plottype=".$plotType;

    echo "</tr>\n";
    echo "</table>\n";
}


###########################################################################
#
# Creates a table title
#
###########################################################################
function createTableTitle($str, $colSpan) {

    global $headerColor;
    echo "<th colspan=\"$colSpan\"bgcolor=\"$headerColor\"><h2>$str</h2></th>";
}

###########################################################################
#
# Creates a table header cell
#
###########################################################################
function createTableColumnHeader($str) {

    global $columnHeaderColor;
    echo "<th bgcolor=\"$columnHeaderColor\"><h3>$str</h3></th>";
}

###########################################################################
#
# Creates table cell with a red background if an error
#
###########################################################################
function createFormattedTableCell($showLink, $link, $str, $error, $color) {

    $fontColor = $error ? "black" : "blue";

    if ($error) echo "<td bgcolor=\"red\">";
    else if ($color) echo "<td bgcolor=\"$color\">";
    else  echo "<td>";
    if ($showLink) echo "<a href=\"$link\"><font color=\"$fontColor\">$str</font></td>";
    else if ($str) echo "$str</td>";
    else echo "&nbsp;</td>";
}


###########################################################################
#
# Returns state and fault-count (if new) as a string
#
###########################################################################
function getStateAndFaults($db, $label, $state, $stage, &$str, &$anyFaults) {

    $anyFaults = false;
    $sql = "SELECT pending, faults FROM $stage WHERE label LIKE '$label' ORDER BY timestamp DESC LIMIT 1";
    if ($debug) {echo "$sql<br>";}

    $qry = $db->query($sql);
    if (dberror($qry)) {echo "<b>error with $sql </b><br>\n";}
    $qry->fetchInto($row);

    $pending = $row[0];
    $faults = $row[1];

    if ($pending == 0)
        $str = "";
    else
        $str = "$pending";

    if ($state == "new") {

        if ($faults > 0) {

            $str = $str."(".$faults.")";
            $anyFaults = true;
        }
    }
}

###########################################################################
#
# Returns time of last czarDb update 
#
###########################################################################
function getLastUpdateTime($db) {

    $anyFaults = false;
    $sql = "SELECT timestamp FROM processed ORDER BY timestamp DESC LIMIT 1";
    if ($debug) {echo "$sql<br>";}

    $qry = $db->query($sql);
    if (dberror($qry)) {echo "<b>error with $sql </b><br>\n";}
    $qry->fetchInto($row);

    return $row[0];
}


?>

