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

$ID = checkID ();

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

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

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

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

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

$userSelection = $_GET[label];

if ($userSelection == "") {$userSelection = $_POST['state'];}
if ($userSelection == "") {$userSelection = "new";}

$debug = 0;

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

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

exec("getLabels.pl -s stdscience", $stdsLabels, $status);
exec("getLabels.pl -s distribution", $distLabels, $status);

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

$states=array("full","new","drop","wait");
$stages=array("chip","cam","fake","warp","stack","diff","magic","destreak","dist");
$servers=array("addstar", "cleanup", "detrend", "distribution", "pstamp", "publishing", "registration", "replication", "stdscience", "summitcopy");
$separator = "-----";
// set up the form
echo "<form action=\"czartool.php\" method=\"POST\">\n";
echo "<select name=state >\n";
echo "<option value=\"none\">Select one...</option>\n";
echo "<option value=\"none\">$separator</option>\n";
foreach ($states as &$state) {echo "<option value=\"$state\">'$state' for all labels</option>\n";}
echo "<option value=\"none\">$separator</option>\n";
echo "<option value=\"servers\">Check all pantasks servers</option>\n";
foreach ($servers as &$server) {echo "<option value=\"$server\">Status for '$server' server</option>\n";}
echo "<option value=\"none\">$separator</option>\n";
foreach ($stdsLabels as &$label) {echo "<option value=\"$label\">$label</option>\n";}

echo "</select>\n";
echo "<input type=submit value=Go>\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";


$stateChosen = 0;
foreach ($states as &$state) {

    if ($userSelection == $state) {
        showAllLabels($pass, $proj, $db, $stdsLabels, $distLabels, $stages, $states, $state); 
        $stateChosen=1;
        break;
    }
}

$serverChosen = 0;
foreach ($servers as &$server) {

    if ($userSelection == $server) {
        showServerStatus($server); 
        $serverChosen=1;
        break;
    }
}
if (!$stateChosen && !$serverChosen) {

    if ($userSelection == "servers") {showAllServerStatus($servers); }// TODO
    elseif ($userSelection == $separator) {}
    else { showOneLabel($pass, $proj, $db, $userSelection, $stages, $states);}

}
menu_end();

###########################################################################
#
# Shows the status of the provided pantasks server 
#
###########################################################################
function showServerStatus($server) {

    echo "<p> Status for $server server </p>";

    $results=array();
    exec("getServerStatus.pl -s $server", $results, $status);

    foreach ($results as &$line) {
        echo "<pre>\n";
        echo "$line\n";
        echo "</pre>\n";

    }

}

###########################################################################
#
# Checks the status of all the pantasks servers 
#
###########################################################################
function showAllServerStatus($servers) {

    echo "<p> Status for all pantasks servers </p>";

    // set up table columns
    $class = "list";
    echo "<table class=list>\n";
    echo "<tr><td></td>\n";
    write_header_cell($class, "Server");
    write_header_cell($class, "Alive?");
    write_header_cell($class, "Scheduler running?");
    echo "</tr>\n";

    foreach ($servers as &$server) {

        $results=array();
        exec("checkServer.pl -s $server", $results, $status);

        echo "<tr><td></td>\n";
        write_table_cell($class, '%s', "", $server);
        write_table_cell($class, '%s', "", $results[0]);
        write_table_cell($class, '%s', "", $results[1]);
        echo "</tr>\n";
    }

    echo "</table>\n";
}


###########################################################################
#
# Checks one label and prints results in a table
#
###########################################################################
function showOneLabel($pass, $proj, $db, $label, $stages, $states) {

    echo "<p> Current status for label '$label' (any faults are shown in parentheses) </p>";

    // set up table columns
    $class = "list";
    echo "<table class=list>\n";
    echo "<tr><td></td>\n";
    write_header_cell($class, "state");
    foreach ($stages as &$stage) {write_header_cell($class, $stage);}
    echo "</tr>\n";

    // write rows
    foreach ($states as &$state) {

        $link = "czartool.php?pass=" . $pass . "&proj=" . $proj . "&label=" . $state;

        echo "<tr><td></td>\n";
        write_table_cell($class, '%s', $link, $state);
        write_table_cell($class, '%s', "", getStateAndFaults($db, $label,"chipRun", $state, "chip"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $label,"camRun", $state, "cam"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $label,"fakeRun", $state, "fake"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $label,"warpRun", $state, "warp"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $label,"stackRun", $state, "stack"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $label,"diffRun", $state, "diff"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $label,"magicRun", $state, "magic"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $label,"magicDSRun", $state, "magicDS"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $label,"distRun", $state, "dist"));
        echo "</tr>\n";
    }

    echo "</table>\n";
}

###########################################################################
#
# Creates table for all labels showing all stages for given 'state'
#
###########################################################################
function showAllLabels($pass, $proj, $db, $stdsLabels, $distLabels, $stages, $states, $selectedState) {

    echo "<p> Current stdscience labels for '$selectedState' (any faults are shown in parentheses)</p>";

    // set up table columns
    $class = "list";
    echo "<table class=list>\n";
    echo "<tr><td></td>\n";
    write_header_cell($class, "label");
    write_header_cell($class, "distributing?");
    //    echo "<td class=\"$class\"><a href=\"$link\"> $myValue </a></td>\n";
    //    echo "<th class=\"$class\"><a href=\"czartool.php\">label</th>\n";

    foreach ($stages as &$stage) {write_header_cell($class, $stage);}
    //foreach ($stages as &$stage) {

    //  $link = "czartool.php?pass=" . $pass . "&proj=" . $proj . "&label=" . $stage;
    // echo "<th class=\"$class\"><a href=\"$link\">$stage</th>\n";
    // }

    echo "</tr>\n";

    // write rows
    foreach ($stdsLabels as &$stdsLabel) {

        $distributing = false;
        foreach ($distLabels as &$distLabel) {

            if ($stdsLabel == $distLabel) { $distributing = true; break;}
        }


        // create link to label summary page for each label
        $link = "czartool.php?pass=" . $pass . "&proj=" . $proj . "&label=" . $stdsLabel;

        echo "<tr><td></td>\n";
        write_table_cell($class, '%s', $link, $stdsLabel);
        write_table_cell($class, '%s', "", $distributing ? "yes" : "NO");
        write_table_cell($class, '%s', "", getStateAndFaults($db, $stdsLabel,"chipRun", $selectedState, "chip"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $stdsLabel,"camRun", $selectedState, "cam"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $stdsLabel,"fakeRun", $selectedState, "fake"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $stdsLabel,"warpRun", $selectedState, "warp"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $stdsLabel,"stackRun", $selectedState, "stack"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $stdsLabel,"diffRun", $selectedState, "diff"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $stdsLabel,"magicRun", $selectedState, "magic"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $stdsLabel,"magicDSRun", $selectedState, "magicDS"));
        write_table_cell($class, '%s', "", getStateAndFaults($db, $stdsLabel,"distRun", $selectedState, "dist"));
        echo "</tr>\n";
    }

    echo "</table>\n";
}

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

    $new = checkLabel($db, $label, $table, $state, $stage);

    if ($state != "new") {return $new;}

    $faults = countFaults($db, $label,$table,$stage);

    if ($faults < 1) {return $new;}

    return $new."(".$faults.")";
}

###########################################################################
#
# Returns count of exposures with this state for this label
#
###########################################################################
function checkLabel($db, $label, $table, $state, $stage) {

    $sql = "SELECT COUNT(state) FROM $table WHERE label LIKE '$label' AND state = '$state'";
    if ($debug) {echo "$sql<br>";}

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

###########################################################################
#
# Returns count of faults for this stage and label
#
###########################################################################
function countFaults($db, $label, $table, $stage) {

    $joinTable = 0;
    $id = $stage."_id";

    if ($stage == "chip") {$joinTable="chipProcessedImfile";}
    elseif ($stage == "cam") {$joinTable="camProcessedExp";}
    elseif ($stage == "fake") {$joinTable="fakeProcessedImfile";}
    elseif ($stage == "warp") {$joinTable="warpSkyfile";}
    elseif ($stage == "stack") {$joinTable="stackSumSkyfile";}
    elseif ($stage == "diff") {$joinTable="diffSkyfile";}
    elseif ($stage == "magic") {$joinTable="magicNodeResult";}
    elseif ($stage == "magicDS") {$id = "magic_ds_id"; $joinTable="magicDSFile";}
    elseif ($stage == "dist") {$joinTable="distComponent";}
    else {return -1;}

    $faultCol =  $joinTable.".fault";

    $sql = "SELECT COUNT(DISTINCT $id) FROM $table JOIN $joinTable USING ($id) WHERE label LIKE '$label' AND $faultCol != 0 AND $table.state = 'new'";
    if ($debug) {echo "$sql<br>";}

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

