<?php
exec("docker ps -aq", $res, $ret);
if ($ret!=0) exit(1);
exec("docker inspect ".join(" ", $res), $res2, $ret);
if ($ret!=0) exit(1);
$containers=json_decode(join($res2), true);
echo "<table class=\"manage docker\"><thead>\n";
echo "<tr><th>Name</th><th>Ports</th><th>Links</th><th>Image</th><th>Actions</th></tr>\n";
echo "</thead><tbody>";
foreach ($containers as $c) {
  $name = preg_replace(',^/,', '', $c['Name']);
  $ports = "<ul>";
  if ($c['NetworkSettings']['Ports']) {
    foreach ($c['NetworkSettings']['Ports'] as $from => $to) {
      if ($to)
        foreach ($to as $p) {
          if (isset($p['HostPort']))
            $ports.="<li>".($p['HostIp']!="0.0.0.0"?$p['HostIp'].":":"").$p['HostPort'].':'.$from.'</li>';
        }
    }
  } elseif ($c['HostConfig']['PortBindings']) {
    foreach ($c['HostConfig']['PortBindings'] as $from => $to) {
      if ($to)
        foreach ($to as $p) {
          if (isset($p['HostPort']))
            $ports.="<li>".($p['HostIp']&&$p['HostIp']!="0.0.0.0"?$p['HostIp'].":":"").$p['HostPort'].':'.$from.'</li>';
        }
    }
  }
  $ports .= "</ul>";
  $links = "<ul>";
  if ($c['HostConfig']['Links'])
    foreach ($c['HostConfig']['Links'] as $link)
      $links.="<li>".preg_replace(',^/?(.*):/?'.$name.'/?(.*)$,', '${1}:${2}', $link)."</li>";
  $links .= "</ul>";
  $image = $c['Config']['Image'];
  if ($c['State']['Dead']) {$status = "dead"; $actions=Array("start", "rm");}
  elseif ($c['State']['Restarting']) {$status = "restarted"; $actions=Array();}
  elseif ($c['State']['Paused']) {$status = "paused"; $actions=Array("unpause", "rm");}
  elseif ($c['State']['Running']) {$status = "running"; $actions=Array("pause", "stop");}
  else {$status="dead"; $actions=Array("start", "rm");}
  $action="";
  foreach($actions as $a)
    $action.='<a class="toolbutton" href="javascript:action('."'".$c['Id']."', '".$a."'".');">'.$a.'</a>';
  echo '<tr class="'.$status.'"><td><a href="javascript:details('."'".$c['Id']."'",')">'.$name.'</a></td><td>'.$ports.'</td><td>'.$links.'</td><td>'.$image.'</td><td class="buttongroup">'.$action.'</td></tr>'."\n";
}
echo "</tbody></table>";
?>