<?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']);

$states=array("full","new","drop","wait");
$stages=array("burntool", "chip","cam","fake","warp","stack","diff","magic","magicDS","dist");
$servers=array(
        "addstar",
        "cleanup",
        "detrend",
        "distribution",
        "pstamp",
        "update",
        "publishing",
        "registration",
        "replication",
        "stdscience",
        "summitcopy");

$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];

if ($selectedLabel == "") { $selectedLabel = "all_stdscience_labels"; }
if ($selectedStage == "") { $selectedStage = "all_stages"; }
if ($plotType == "") { $plotType = "linear"; }

$nsStatus = getNightlyScienceStatus($czardb);
$plotTypeLink = ($plotType == "linear") ? "log" : "linear";
$link = "czartool_labels.php?pass=" . $pass . "&proj=" . $proj . "&label=" . $selectedLabel . "&stage=" . $selectedStage . "&revertstage=" . $stage . "&plottype=$plotTypeLink";
echo "<p>Current ippMonitor SVN version: ";
include 'version.php';
echo "</p>";
echo "<p  align=\"center\"> Current status of the IPP as of $lastUpdateTime (faults are shown in parentheses). <br>Documentation can be found <a href=\"http://svn.pan-starrs.ifa.hawaii.edu/trac/ipp/wiki/Processing\">here</a> and cluster load monitored <a href=\"http://ganglia.pan-starrs.ifa.hawaii.edu/?r=hour&s=descending&c=IPP%2520Production\">here</a><br>Current nightly science status: $nsStatus<br>Use <a href=\"$link\"> $plotTypeLink</a> plots <br/><a href=\"http://ipp004.ifa.hawaii.edu/clusterMonitor/top.html\">Who uses the cluster?</a><br><a href=\"http://ipp004.ifa.hawaii.edu/ippMetrics\">IPP Metrics</a><br/><a href=\"http://svn.pan-starrs.ifa.hawaii.edu/trac/ipp/wiki/PS1_IPP_CzarLogs\">Czar log pages</a><br><a href=\"czartool_exposures.php?pass=$pass&proj=$proj\">Exposure summary</a></p>";

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

$stdsLabels = getLabels($czardb, "stdscience");
$distLabels = getLabels($czardb, "distribution");
$pubLabels = getLabels($czardb, "publishing");
$updateLabels = getLabels($czardb, "update");

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


// set up the form
echo "<form action=\"czartool_labels.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>\n";


  # 1st row
    echo "<tr>\n";
      echo "<td> \n";
        echo "<table>\n";
          echo "<tr valign=center>\n";
            echo "<td> \n";
              # timeseries plot
              echo "<img src=\"czartool_getplot.php?type=t&label=$selectedLabel&stage=$selectedStage&plottype=$plotType\"><br>";
            echo "</td>\n";
            echo "<td>\n";
              createLabelsTable($pass, 
                      $proj, 
                      $czardb, 
                      "stdscience", 
                      $stdsLabels, 
                      $distLabels, 
                      $pubLabels, 
                      $stages, 
                      $states, 
                      "new", 
                      $selectedLabel, 
                      $selectedStage, 
                      $plotType);
            echo "</td>\n";
          echo "</tr>\n";
        echo "</table>\n";
      echo "</td> \n";
    echo "</tr>\n";



    # 2nd row
    echo "<tr>\n";
      echo "<td> \n";
        echo "<table>\n";
          echo "<tr valign=center>\n";
            echo "<td> \n";
              # rate plot
              echo "<img src=\"czartool_getplot.php?type=r&label=$selectedLabel&stage=$selectedStage&plottype=linear\"><br>";
            echo "</td>\n";
            echo "<td>\n";
            createLabelsTable($pass, 
                    $proj, 
                    $czardb, 
                    "update", 
                    $updateLabels, 
                    $distLabels, 
                    $pubLabels, 
                    $stages, 
                    $states, 
                    "new", 
                    $selectedLabel, 
                    $selectedStage, 
                    $plotType);
            echo "</td>\n";
          echo "</tr>\n";
        echo "</table>\n";
      echo "</td> \n";
    echo "</tr>\n";


    # 3rd row
    echo "<tr>\n";
      echo "<td> \n";
        echo "<table>\n";
          echo "<tr valign=top>\n";
            echo "<td> \n";
              # histogram plot
              echo "<img src=\"czartool_getplot.php?type=h&label=$selectedLabel&stage=$selectedStage&plottype=linear\"><br>";
            echo "</td>\n";
            echo "<td>\n";
              createServersTable($pass, $proj,$czardb, $servers, $selectedLabel, $selectedStage, $plotType);
            echo "</td>\n";

            echo "<td> \n";
              $today = date("Y-m-d");
              createSummitDataTable($gpc1db, $today);
            echo "</td>\n";
          echo "</tr>\n";
        echo "</table>\n";
      echo "</td> \n";
    echo "</tr>\n";

    # 4th row
    echo "<tr>\n";
      echo "<td> \n";
        echo "<table>\n";
          echo "<tr valign=top>\n";
            echo "<td> \n";
              # storage plot
              echo "<img src=\"czartool_getplot.php?type=s\"><br>";
            echo "</td>\n";
            echo "<td>\n";
              createDatesTable($czardb);
            echo "</td>\n";
          echo "</tr>\n";
        echo "</table>\n";
      echo "</td> \n";
    echo "</tr>\n";

    # 5th row
    echo "<tr>\n";
      echo "<td>\n";
        echo "<table>\n";
          echo "<tr valign=top>\n";
            echo "<td> \n";
              if ($selectedServer && !$serverCmd) showServerStatus($selectedServer);
            echo "</td>\n";
            echo "<td>\n";
            # This is awful
              echo "<table border=\"1\"><tr><td colspan=\"2\"><b>Databases Replication Status</b></td></tr>";
                echo "<tr><td colspan=\"2\">Update fix log <a href=\"http://svn.pan-starrs.ifa.hawaii.edu/trac/ipp/wiki/Replication_Issues\">here</a></td></tr>";
                echo "<tr><td>Database</td><td>Replication Status</td></tr>";
                showReplicationsStatus($REPL_HOST_GPC1, $REPL_USER_GPC1, $REPL_PASSWORD_GPC1, $REPL_DBNAME_GPC1);
                showReplicationsStatus($REPL_HOST_NEBULOUS, $REPL_USER_NEBULOUS, $REPL_PASSWORD_NEBULOUS, $REPL_DBNAME_NEBULOUS);

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

  echo "</table>\n";

menu_end();


###########################################################################
#
# Creates a table of summitExp against rawExp
#
###########################################################################
function createSummitDataTable($gpc1db, $date) {

    $sql = "SELECT DISTINCT exp_type FROM summitExp WHERE dateobs > '$date'";

    $qry = $gpc1db->query($sql);
    if (dberror($qry)) {
        echo "<b>error reading newExp table</b><br>\n";
        echo "<br><small><b> table query : $sql </b></small><br>\n";
        menu_end();
    }

    // set up the table
    echo "<table class=list>\n";
    echo "<tr><td></td>\n";
    write_header_cell ("list", "Exposure type");
    write_header_cell ("list", "At summit");
    write_header_cell ("list", "Registered at MHPCC");

    $msg = "No science images taken since $date";

    // list the results
    while ($qry->fetchInto($expType)) {

        $sql = "SELECT COUNT(*) FROM summitExp WHERE dateobs > '$date' AND exp_type = '$expType[0]'";
        $qry2 = $gpc1db->query($sql);
        $qry2->fetchInto($summit);
        $sql = "SELECT COUNT(*) FROM summitExp JOIN rawExp ON summitExp.exp_name = rawExp.exp_name WHERE summitExp.dateobs > '$date' AND summitExp.exp_type = '$expType[0]'";
        $qry2 = $gpc1db->query($sql);
        $qry2->fetchInto($mhpcc);

        $class = "list";
        echo "<tr><td></td>\n";

        if ($expType[0] == "OBJECT") {
	  if ($summit[0] == $mhpcc[0]) {
	    $msg = "All science exposures taken since $date<br>have been registered at MHPCC";
	  }
	  else {
	    $msg = "<font color=\"orange\">Warning: Not all science exposures taken since $date<br>have been registered at MHPCC</a>";
	  }
        }

        write_table_cell ($class, '%s', "", $expType[0]);
        write_table_cell ($class, '%d', "", $summit[0]);
        write_table_cell ($class, '%d', $link, $mhpcc[0]);
        echo "</tr>\n";
    }

    echo "</table>\n";

    echo "<p> $msg </p>";

}

###########################################################################
#
# Gets labels for this server
#
###########################################################################
function getLabels($db, $server) {

    # order by descending priority as set in gpc1 database
    $sql = "SELECT label FROM current_labels WHERE server LIKE '$server' ORDER BY priority DESC";
    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, 
        $server, 
        $labels, 
        $distLabels, 
        $pubLabels, 
        $stages, 
        $states, 
        $selectedState, 
        $selectedLabel, $selectedStage, $plotType) {

    // set up table columns
    $class = "list";
    echo "<table class=$class >\n";
    echo "<tr><td></td>\n";

    echo "<p  align=\"center\"> Current labels for $server server (D=distributing, P=publishing)</p>";

    write_header_cell($class, "");
    write_header_cell($class, "");
    write_header_cell($class, "Reverts:");
    foreach ($stages as &$stage) {

        if ($stage == "burntool") continue;
        $reverting = getRevertStatus($db, $stage);
        $link = 
            "czartool_labels.php?pass=".$pass
            ."&proj=".$proj
            ."&label=".$selectedLabel
            ."&stage=".$selectedStage
            ."&plottype=".$plotType
            ."&revertstage=".$stage
            ."&revertmode=";

        if(!$reverting) {$label =  "Start";$link = $link . "on";}
        if($reverting) {$label = "Stop";$link = $link . "off";}
        unset($reverting);
        write_table_cell($class, '%s', $link, $label);
    }
    write_header_cell($class, "");

    echo "</tr>\n";
    echo "<tr><td></td>\n";
    write_header_cell($class, " ");
    write_header_cell($class, "Label (in order of priority)");
    foreach ($stages as &$stage) {

        if ($stage == $selectedStage) $link = "";
        else $link = 
            "czartool_labels.php?pass=".$pass
                ."&proj=".$proj 
                ."&label=".$selectedLabel
                ."&stage=".$stage
                ."&plottype=".$plotType;

        write_table_cell($class, '%s', $link, $stage);
    }

    if ($selectedStage=="all_stages") $link = "";
    else $link = 
        "czartool_labels.php?pass=".$pass
            ."&proj=".$proj
            ."&label=".$selectedLabel
            ."&stage=all_stages"
            ."&plottype=".$plotType;

    write_table_cell($class, '%s', $link, "All stages");

    echo "</tr>\n";
    echo "<tr><td></td>\n";

    $defaultlink = 
        "czartool_labels.php?pass=".$pass
        ."&proj=".$proj
        ."&label=".$selectedLabel
        ."&stage=".$selectedStage
        ."&plottype=".$plotType;

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

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

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

            if ($thisLabel == $distLabel) { $distributing = true; break;}
        }
        foreach ($pubLabels as &$pubLabel) {

            if ($thisLabel == $pubLabel) { $publishing = true; break;}
        }

        // create link to label summary page for each label
        if ($thisLabel == $selectedLabel) $link = "";
        else $link = 
            "czartool_labels.php?pass=".$pass
                ."&proj=".$proj
                ."&label=".$thisLabel
                ."&stage=".$selectedStage
                ."&plottype=".$plotType;

        echo "<tr><td></td>\n";
        $distPub = " ";
        if ($distributing) $distPub = "D";
        if ($publishing) $distPub = $distPub . "P";
        write_table_cell($class, '%s', "", $distPub);

        write_table_cell($class, '%s', $link, $thisLabel);

        $str = "";
        $anyFaults = false; 

        $link = $defaultlink;
        getStateAndFaults($db, $thisLabel, $selectedState, "burntool", $str, $anyFaults);
        write_table_cell($class, '%s', $anyFaults ? $link : "", $str);

        $link = "failedChipProcessedImfile.php?pass=" . $pass . "&proj=" . $proj . "&chipRun.label=" . $thisLabel . "&chipRun.state=".$searchState;
        getStateAndFaults($db, $thisLabel, $selectedState, "chip", $str, $anyFaults);
        write_table_cell($class, '%s', $anyFaults ? $link : "", $str);

        $link = "failedCamProcessedExp.php?pass=" . $pass . "&proj=" . $proj . "&camRun.label=" . $thisLabel . "&camRun.state=".$searchState;
        getStateAndFaults($db, $thisLabel, $selectedState, "cam", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link =  "failedFakeProcessedImfile.php?pass=" . $pass . "&proj=" . $proj . "&fakeRun.label=" . $thisLabel . "&fakeRun.state=".$searchState;
        getStateAndFaults($db, $thisLabel, $selectedState, "fake", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = "failedWarpSkyfiles.php?pass=" . $pass . "&proj=" . $proj . "&warpRun.label=" . $thisLabel . "&warpRun.state=".$searchState;
        getStateAndFaults($db, $thisLabel, $selectedState, "warp", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "",  $str);

        $link = "failedStackSkyfile.php?pass=" . $pass . "&proj=" . $proj . "&stackRun.label=" . $thisLabel . "&stackRun.state=".$searchState;
        getStateAndFaults($db, $thisLabel, $selectedState, "stack", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = "failedDiffSkyfile.php?pass=" . $pass . "&proj=" . $proj . "&diffRun.label=" . $thisLabel . "&diffRun.state=".$searchState;
        getStateAndFaults($db, $thisLabel, $selectedState, "diff", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "",  $str);

        $link = $defaultlink;
        getStateAndFaults($db, $thisLabel, $selectedState, "magic", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = $defaultlink;
        getStateAndFaults($db, $thisLabel, $selectedState, "magicDS", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = $defaultlink;
        getStateAndFaults($db, $thisLabel, $selectedState, "dist", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        echo "</tr>\n";
    }

    if ($selectedLabel == "all_".$server."_labels") $link = "";
    else  $link = "czartool_labels.php?pass=" . $pass . "&proj=" . $proj . "&label=all_".$server."_labels&stage=".$selectedStage."&plottype=".$plotType;

    echo "<tr><td></td>\n";
    write_table_cell($class, '%s', "", " ");
    write_table_cell($class, '%s', $link, "All $server labels");

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

###########################################################################
#
# Sets reverts status 
#
###########################################################################
function setRevertStatus($db, $stage, $reverting) {

    $sql = "UPDATE reverts SET reverting = $reverting WHERE stage LIKE '$stage'";
    if ($debug) {echo "$sql<br>";}

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

###########################################################################
#
# Returns current nightly science status 
#
###########################################################################
function getNightlyScienceStatus($db) {

    $sql = "SELECT status FROM nightlyscience";
    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];
}

###########################################################################
#
#  Turns reverts on or off for a given task
#
###########################################################################
function turnRevertsOnOff($db, $stage, $mode) {

    exec("czartool_revert.pl -t $stage -o $mode", $response, $status);
    $currentRevertMode;
    if ($response[0] == "off") $currentRevertMode = 0;
    else if ($response[0] == "on") $currentRevertMode = 1;

    setRevertStatus($db, $stage, $currentRevertMode);
}

###########################################################################
#
# Returns whether this stage is reverting or not
#
###########################################################################
function getRevertStatus($db, $stage) {

    $anyFaults = false;

    $sql = "SELECT reverting FROM reverts WHERE stage LIKE '$stage'";
    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];
}

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

###########################################################################
#
# Populates a tables with the current dates listed in the server_dates table 
#
###########################################################################
function createDatesTable($db) {

    $class = "list";
    echo "<table class=$class>\n";
    echo "<tr><td></td>\n";
    write_header_cell($class, "Server");
    write_header_cell($class, "Dates");
    echo "</tr>\n";

    createServerDateRow($db, "stdscience");
    createServerDateRow($db, "registration");

    echo "</table>\n";
}


###########################################################################
#
# Checks the status of all the pantasks servers 
#
###########################################################################
function createServerDateRow($db, $server) {

    $sql = "SELECT date FROM server_dates WHERE server LIKE '$server' ORDER BY date";
    if ($debug) {echo "$sql<br>";}

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

        if ($firstIn) {

            $dates = $row[0];
            $firstIn = false;
        }
        else $dates = $dates . ", " . $row[0];
    }

    $class = "list";
    echo "<tr><td></td>\n";
    write_table_cell($class, '%s', "", $server);
    write_table_cell($class, '%s', "", $dates);
    echo "</tr>\n";

}

###########################################################################
#
# Checks the status of all the pantasks servers 
#
###########################################################################
function createServersTable($pass, $proj, $db, $servers, $selectedLabel, $selectedStage, $plotType) {

    // set up table columns
    $class = "list";
    echo "<table class=$class>\n";
    echo "<tr><td></td>\n";
    write_header_cell($class, "Server");
    write_header_cell($class, "Alive?");
    $link = "czartool_labels.php?pass=".$pass
        ."&proj=".$proj
        ."&label=".$selectedLabel
        ."&stage=".$selectedStage
        ."&plottype=".$plotType
        ."&allservercmd=stop";

    $link = ""; # TODO removed links temporarily
        write_table_cell($class, '%s', $link, "Stop all");
    $link = "czartool_labels.php?pass=".$pass
        ."&proj=".$proj
        ."&label=".$selectedLabel
        ."&stage=".$selectedStage
        ."&plottype=".$plotType
        ."&allservercmd=run";

    $link = ""; # TODO removed links temporarily
        write_table_cell($class, '%s', $link, "Run all");
    echo "</tr>\n";

    foreach ($servers as &$server) {

        getServerStatus($db, $server, $alive, $running);

        echo "<tr><td></td>\n";
        $link = "czartool_labels.php?pass=".$pass
            ."&proj=".$proj
            ."&server=".$server
            ."&label=".$selectedLabel
            ."&stage=".$selectedStage
            ."&plottype=".$plotType;

        #$link = ""; # TODO removed links temporarily
        write_table_cell($class, '%s', $link, $server);
        write_table_cell($class, '%s', "", $alive ? "yes" : "NO");

        if ($alive) {

            $link = "czartool_labels.php?pass=".$pass
                ."&proj=".$proj
                ."&label=".$selectedLabel
                ."&stage=".$selectedStage
                ."&plottype=".$plotType
                ."&server=".$server
                ."&servercmd=";

            if ($running)  {

                $link = $link . "stop";
                $link = ""; # TODO removed links temporarily
                    write_table_cell($class, '%s', $link, "stop");
                write_table_cell($class, '%s', "", "");
            }
            else {

                $link = $link . "run";
                write_table_cell($class, '%s', "", "");
                $link = ""; # TODO removed links temporarily
                    write_table_cell($class, '%s', $link, "run");
            }
        }
        else {

            write_table_cell($class, '%s', "", "");
            write_table_cell($class, '%s', "", "");
        }
        echo "</tr>\n";
    }

    echo "</table>\n";
}

###########################################################################
#
#  Commands a server to stop or run 
#
###########################################################################
function serverStopRun($db, $server, $cmd) {

    exec("czartool_serverstoprun.pl -s $server -c $cmd", $response, $status);
    $alive = 0;
    $running = 0;
    if ($response[0] == "running") {$alive = 1; $running = 1;}
    else if ($response[0] == "stopped") {$alive = 1; $running = 0;} 
    else if ($response[0] == "dead") {$alive = 0; $running = 0;}
    setServerStatus($db, $server, $alive, $running);
}

###########################################################################
#
# Sets server status 
#
###########################################################################
function setServerStatus($db, $server, $alive, $running) {

    $sql = "INSERT INTO servers (server, alive, running) VALUES ('$server', $alive, $running)";

    if ($debug) {echo "$sql<br>";}

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


###########################################################################
#
# Returns state and fault-count (if new) as a string
#
###########################################################################
function getServerStatus($db, $server, &$alive, &$running) {

    $sql = "SELECT alive, running FROM servers WHERE server LIKE '$server' 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);

    $alive = $row[0];
    $running = $row[1];
}

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

    $anyFaults = false;
    $sql = "SELECT timestamp FROM chip 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];
}

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

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

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

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

    }
}

###########################################################################
#
# Shows the status of the various replication mysql servers
#
###########################################################################
function showReplicationsStatus($replHost, $replUser, $replPassword, $replDatabaseName) {
    #print "<br>$replHost, $replUser, $replPassword, $replDatabaseName<br/>";
    $dbRepl = DB::connect("mysql://$replUser:$replPassword@$replHost");
    if (PEAR::isError($dbRepl)) {
        die("MySQL DB connection error: Check the configuration for $replDatabaseName");
    }
    $res = $dbRepl->query('SHOW SLAVE STATUS');
    while ($res->fetchInto($row)) {
        # Have a look for Last_Errno in http://dev.mysql.com/doc/refman/5.0/en/show-slave-status.html
        $errorStatusInMySql = $row[18];
        $replStatus = ($errorStatusInMySql==0?"OK":"<font color=\"red\">PROBLEM</font>");
        echo "<tr><td>$replDatabaseName</td><td>$replStatus</td></tr>";
        if ($errorStatusInMySql!=0) {
            echo "<tr><td colspan=\"2\">Connect to $replDatabaseName replication host, execute 'SHOW SLAVE STATUS', and fix the problem.<br/>";
            echo "Information <a href=\"http://dev.mysql.com/doc/refman/5.0/en/show-slave-status.html\">here</a></td></tr>";
        }
    }
    $dbRepl->disconnect();
}

?>

