<?php

require_once "WEB-INF/php/inc.php";

if (! admin_init()) {
  return;
}

$webapp = $g_mbean_server->lookup($_GET['id']);

$request = quercus_servlet_request();
$is_secure = $request->isSecure();
$user = quercus_get_request()->getUserPrincipal();

if ($is_secure) {
  $action = $_POST['action'];

  if ($action == "start") {
    $mbean = $g_mbean_server->lookup($_POST['name']);
    $mbean->start();
  }
  elseif ($action == "stop") {
    $mbean = $g_mbean_server->lookup($_POST['name']);
    $mbean->stop();
  }
  elseif ($action == "restart") {
    $mbean = $g_mbean_server->lookup($_POST['name']);
    $mbean->restart();
  }
}

if ($webapp) {
  display_webapp_page($g_mbean_server, $webapp);
}
else {
  display_webapp_summary_page($g_mbean_server);
}

/**
 * single-page webapp
 */
function display_webapp_page($mbean_server, $webapp)
{
  global $is_secure;

  $session = $webapp->SessionManager;
  
  echo "<h2>WebApp";
  print_help("WebApp");
  echo "</h2>\n";

  echo <<<END
<table class="data">
  <tr>
    <th>Web-App</th>
    <th>State</th>
    <th>Active</th>
    <th>Sessions</th>
    <th>Uptime</th>
    <th colspan='2'>500</th>
  </tr>
END;

  echo "<tr class='" . row_style($count++) . "'>\n";
  echo " <td class='item'>\n";

  $context_path = empty($webapp->ContextPath) ? "/" : $webapp->ContextPath;

  echo $context_path;

  echo " </td>";

  echo "  <td class='" . format_state_class($webapp->State) . "'>\n";
  echo  $webapp->State;
  echo "  </td>\n";
  echo "  <td>" . $webapp->RequestCount . "</td>\n";
  echo "  <td>" . $session->SessionActiveCount . "</td>\n";
  echo "  <td class='" . format_ago_class($webapp->StartTime) . "'>\n";

  if ($webapp->State == "ACTIVE")
    echo "  Z  " . format_ago($webapp->StartTime) . "\n";
  else
    echo "&nbsp;";
    
  echo "   </td>\n";

        format_ago_td_pair($webapp->Status500CountTotal,
                           $webapp->Status500LastTime);

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

  echo "<h3>Actions</h3>\n";

  if ($is_secure) {
    $disabled = "";
  }
  else {
    $disabled = "disabled='true'";
    echo "<div class='warn'>Actions can only be performed over a secure connection (SSL)</div>";
  }

  $name = $webapp->mbean_name;

  echo "<form method='POST' style='display:inline'>\n";
  echo "<input type='hidden' name='action' value='start'>\n";
  echo "<input type='hidden' name='name' value='$name'>\n";
  if ($webapp->State == "ACTIVE")
    echo "<input type='submit' name='submit' value='start' disabled='true'>\n";
  else
    echo "<input type='submit' name='submit' value='start' $disabled>\n";
  echo "</form>";

  echo "<form method='POST' style='display:inline'>\n";
  echo "<input type='hidden' name='action' value='stop'>\n";
  echo "<input type='hidden' name='name' value='$name'>\n";
  if ($webapp->State == "ACTIVE")
    echo "<input type='submit' name='submit' value='stop' $disabled>\n";
  else
    echo "<input type='submit' name='submit' value='stop' disabled='true'>\n";
  echo "</form>";

  echo "<form method='POST' style='display:inline'>";
  echo "<input type='hidden' name='action' value='restart'>";
  echo "<input type='hidden' name='name' value='$name'>\n";
  if ($webapp->State == "ACTIVE")
    echo "<input type='submit' name='submit' value='restart' disabled='true'>\n";
  else
    echo "<input type='submit' name='submit' value='restart' $disabled>";
  echo "</form>";

  echo "<h2>MBeans</h2>\n";

  $exp = mbean_explode($name);
  $beans = $mbean_server->query("resin:*,Host=" . $exp['Host']
                                 . ",WebApp=" . $exp['name']);

  display_jmx($mbean_server, $beans);
}

function display_tab($name, $un_name, $is_selected)
{
  echo "<li id='tab_" . $name . "' class='";
  
  if ($is_selected) {
    echo "selected";
  } 
 
  echo "'><a href='#' onclick=\"";
  echo "sel('tab_" . $name . "');";
  echo "show('g_" . $name . "');";
  
  echo "unsel('tab_" . $un_name . "');";
  echo "hide('g_" . $un_name . "');";

  echo "\">" . $name . "</a></li>\n";
}

/**
 * summary of all the webapps
 */
function display_webapp_summary_page($g_mbean_server)
{
  echo "<div id='webapp-tabs' style='display: none'>\n";
  echo "<ul>\n";
  echo "<li><a href='#webapp-active'>Active</a></li>\n";
  echo "<li><a href='#webapp-idle'>Idle</a></li>\n";
  echo "</ul>\n";

  echo "<div id='webapp-active'>\n";
  display_webapp_summary($g_mbean_server, false);
  echo "</div>\n";
  
  echo "<div id='webapp-idle'>\n";
  display_webapp_summary($g_mbean_server, true);
  echo "</div>\n";

  echo "</div>\n";
}  

/**
 * summary of all the webapps
 */
function display_webapp_summary($g_mbean_server, $is_idle)
{
  global $is_secure;
  
  echo "<h2>WebApps";
  print_help("WebApp");
  echo "</h2>\n";
  
?>

<!-- Applications -->

<table class="data">
  <tr>
    <th></th>
    <th title='The context root of the application'>Web-App</th>
    <th title='The current status of the application'>State</th>
    <th title='How long the application has been running'>Uptime</th>
    <th colspan='2' title='The number of HTTP 5xx errors the application has experienced and the time of the most recent 5xx error'>500</th>
    <th title='Version of cluster-wide deployment, where applicable'>Deploy</th>
    <th title='Start, stop, and restart the application on the current server'>Actions</th>
  </tr>
<?php

  if ($g_mbean_server) {
    $hosts = $g_mbean_server->query("resin:*,type=Host");
  }

  $webapp_id = 0;

  usort($hosts, "sort_host");

  foreach ($hosts as $host) {
    $hostName = empty($host->HostName) ? "default" : $host->HostName;

    echo "<tr><td class='group' colspan='8'>\n";
    echo $host->URL;
    echo "</td></tr>\n";

    $webapps = $host->WebApps;

    usort($webapps, "sort_webapp");
    $count = 0;
    foreach ($webapps as $webapp) {
      if ($is_idle != ($webapp->State == "STOPPED_IDLE")) {
        continue;
      }

      $webapp_name = $webapp->mbean_name;
      $webapp_id++;

      $id = "sw_webapp_" . ($is_idle ? "idle" : "") . $webapp_id;

      echo "<tr class='" . row_style($count++) . "'>";
      echo "<td><span id='${id}' class='switch'></td>\n";

      $is_deploy_valid = true;
      display_webapp($webapp, $is_deploy_valid);
  
      echo "</tr>\n";
      
      echo "<tr class='toggle-${id}'>";
      echo "<td>&nbsp;</td><td colspan='7'>";

      display_webapp_expanded($webapp, $webapp_id, $is_deploy_valid);
      
      echo "</tr>\n";
    }
  }

  echo "</table>\n";
}

function display_webapp($webapp, &$is_deploy_valid)
{
  $session = $webapp->SessionManager;
  $context_path = empty($webapp->ContextPath) ? "/" : $webapp->ContextPath;

  if ($webApp->RepositoryTag) {
    $context_path .= "<br/>&nbsp;&nbsp;(tag: {$webapp->RepositoryTag})";
  }

  $object_name = $webapp->mbean_name;

  echo "<td class='item'>";
  echo $context_path;
  echo "</td>";
  
  echo "<td>";

  if ($webapp->State == "ACTIVE") {
    print_ok("");
    echo " ACTIVE";
  }
  else if ($webapp->State == "FAILED") {
    print_fail(" FAILED");
    $is_deploy_valid = false;
  }
  else {
    echo "&nbsp;" . $webapp->State;
  }
  
  echo "</td>\n";
  ?>
    </td>
    <td class='<?= format_ago_class($webapp->StartTime) ?>'>
      <?
         if ($webapp->State == "ACTIVE")
           echo format_ago($webapp->StartTime)
         else
           echo "&nbsp;";
      ?>
    </td>
  <?php
  format_ago_td_pair($webapp->Status500CountTotal,
                     $webapp->Status500LastTime);

  echo "<td>";

  $deploy = validate_version($webapp);
  
  if ($deploy["version"])
    $version = $deploy["version"];
  else
    $version = $deploy["date"];

  if (! $deploy) {
    $is_deploy_valid = false;
  }
  else if ($deploy["status"] == "OK") {
    print_ok("");
    
    echo " $version";
  }
  else {
    $is_deploy_valid = false;

    print_fail(" $version");
  }
  
  echo "</td>";

  $name = $webapp->mbean_name;

  echo "<td>";
  echo "<form method='POST' style='display:inline'>\n";
  echo "<input type='hidden' name='action' value='start'>\n";
  echo "<input type='hidden' name='name' value='$name'>\n";
  if ($webapp->State == "ACTIVE")
    echo "<input type='submit' name='submit' value='start' disabled='true'>\n";
  else
    echo "<input type='submit' name='submit' value='start' $disabled>\n";
  echo "</form>";

  echo "<form method='POST' style='display:inline'>\n";
  echo "<input type='hidden' name='action' value='stop'>\n";
  echo "<input type='hidden' name='name' value='$name'>\n";
  if ($webapp->State == "ACTIVE")
    echo "<input type='submit' name='submit' value='stop' $disabled>\n";
  else
    echo "<input type='submit' name='submit' value='stop' disabled='true'>\n";
  echo "</form>";

  echo "<form method='POST' style='display:inline'>";
  echo "<input type='hidden' name='action' value='restart'>";
  echo "<input type='hidden' name='name' value='$name'>\n";
  if ($webapp->State == "ACTIVE")
    echo "<input type='submit' name='submit' value='restart' $disabled>";
  else
    echo "<input type='submit' name='submit' value='restart' disabled='true'>\n";
  echo "</form>";
  echo "</td>";
}

function validate_version($webapp)
{
  global $g_mbean_server;
  global $g_server;

  $repository = $webapp->getRepositoryMetaData();

  if (! $repository || ! $repository["root"]) {
    return null;
  }
  else {
    $status = "OK";
    $hash = $repository["root"];

    foreach ($g_server->SelfServer->Cluster->Servers as $s) {
      $mbean_server = new MBeanServer($s->Name);
      $s_webapp = $mbean_server->lookup($webapp->mbean_name);

      if (! $s_webapp) {
        $status = "FAIL";
        continue;
      }
      
      $s_repository = $s_webapp->getRepositoryMetaData();

      if ($s_repository["root"] != $repository["root"]) {
        $status = "FAIL";
      }
    }
    
    return array(status => $status,
                 hash => $repository["root"],
                 version => $repository["version"],
                 date => $repository["date"]);
  }
}

function display_webapp_expanded($webapp, $webapp_id, $is_deploy_valid)
{
  global $g_mbean_server;
  global $g_server;

  $session = $webapp->SessionManager;

  if ($webapp->ErrorMessage) {
    echo "<div class='warn'>";
    echo htmlspecialchars($webapp->ErrorMessage);
    echo "</div>";
  }

  display_versions($webapp, $webapp_id, $is_deploy_valid);

  $exp = mbean_explode($webapp->mbean_name);
  $query = "resin:*,Host=" . $exp['Host'] . ",WebApp=" . $exp['name'];
  $beans = $g_mbean_server->query($query);

  array_push($beans, $webapp);

  echo "<div class='application-usage'>\n";
  echo "<h3>Client activity</h3>";
  echo "<table>\n";
  echo "<tr><th>Active Requests</th><td>{$webapp->RequestCount}</td></tr>\n";
  echo "<tr><th>Active Sessions</th><td>{$session->SessionActiveCount}</td></tr>\n";
  echo "</table>\n";
  echo "</div>\n";

  echo "<div class='application-jmx'>";
  echo "<h3>Application MBeans</h3>";
  display_jmx($g_mbean_server, $beans);
  echo "</div>";

  echo "<p>";
  display_webapp_expanded_actions($webapp, $beans, $refresh_id);
}

function display_webapp_expanded_actions($webapp, $beans, $refresh_id)
{
  global $g_server;
  global $is_secure;

  if ($is_secure) {
    $disabled = "";
  }
  else {
    $disabled = "disabled='true'";
    echo "<div class='warn'>Actions can only be performed over a secure connection (SSL)</div>";
  }

  $name = htmlspecialchars($webapp->mbean_name);

  $server_name = $g_server->SelfServer->Name;
  if (! $server_name)
    $server_name = "default";

  $context_path = empty($webapp->ContextPath) ? "/" : $webapp->ContextPath;
?>
  <h3>Update</h3>
  <form method='GET'>
    <input type='hidden' name='q' value='deploy'/>
    <input type='hidden' name='update-name' value="<?= $context_path ?>"/>
    <button style="padding: 1em;">Update this application</button>
  </form>
  <p></p>
<?
  /*
  echo "<div class='update-application'>";
  echo "<h3>Update</h3>";
  echo "<form method='POST'>";
  echo "<input type='hidden' name='stage' value='{$g_server->Stage}'>";
  echo "<input type='hidden' name='host' value='{$webapp->Host->Name}'>";
  echo "<input type='hidden' name='action' value='update'>";
  echo "<input type='hidden' name='name' value='{$webapp->ContextPath}'>\n";

  echo "<h4>Commit message</h4>";
  echo "<textarea name='commit-message'></textarea>\n";
  echo "<h4>Version</h4>";

  echo "<input type='number' min='0' size='3' name='version-major' title='Major Version Number' value='0' class='required'>\n";
  echo "<input type='number' min='0' size='3' name='version-minor' title='Minor Version Number' value='0' class='required'>\n";
  echo "<input type='number' min='0' size='3' name='version-micro' title='Micro Version Number' value='0' class='required'>\n";
  echo "<input type='text' name='version-qualifier' title='Version Qualifier (free form)' value=''>\n";

  echo "<h4>Application archive file</h4>";
  echo "<input type='file' name='application'>\n";
  echo "<div style='text-align: right'>";
  echo "<input type='submit' name='submit' value='update' $disabled>";
  echo "</div>";
  echo "</form>";
  echo "</div>";*/
}

function display_versions($webapp, $webapp_id, $is_deploy_valid)
{
  global $g_server;

  $repository = $webapp->getRepositoryMetaData();

  if (! $repository || ! $repository["root"]) {
    return;
  }

  echo "<table>";
  echo "<tr><td>";
  echo "<span id='sw_deploy_${webapp_id}' class='switch'></span>\n";
  echo "</td>\n";
  echo "<th>Deploy</th>";
  echo "<th>";

  $root = $repository["root"];

  if ($repository["version"])
    $msg = $repository["version"];
  else
    $msg = $repository["date"];

  if ($is_deploy_valid)
    print_ok($msg);
  else
    print_fail($msg);

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

  foreach ($g_server->SelfServer->Cluster->Servers as $s) {
    $s_mbean_server = new MBeanServer($s->Name);

    $s_webapp = $s_mbean_server->lookup($webapp->mbean_name);

    echo "<tr class='toggle-sw_deploy_${webapp_id}'><td></td>";

    $name = $s->Name;
    if (! $name)
      $name = "default";
      
    printf("<td>%02d - %s</td>", $s->SelfServer->ClusterIndex, $name);

    echo "<td>";
    if ($s_webapp) {
      $s_repository = $s_webapp->getRepositoryMetaData();

      if ($s_repository["version"]) {
        $msg = $s_repository["version"];         
      }
      else if ($s_repository["date"]) {
        $msg = $s_repository["date"];
      }
      else {
        $msg = "not deployed";
      }

      if ($s_repository["root"] == $root) {
        print_ok($msg);
      }
      else {
        print_fail($msg);
      }
    }
    else {
      print_fail("--");
    }
    echo "</td>";

    echo "</tr>\n";
  }

  echo "</table>\n";
}

$javascript = javascript_create_tab("webapp-tabs");

display_footer($g_page, $javascript);
?>
