<?php
exec("docker ps -aq", $res, $ret);
if ($ret!=0) {
  echo '  A [label="Error\nCannot get Docker Containers"];';
  echo '  B [label="Does the Webserver have Docker rights?"];';
  echo '  A->B [label="Probable\nCause"];';
  return;
}
exec("docker inspect ".join(" ", $res), $res2, $ret);
if ($ret==0) {
  $containers=json_decode(join($res2), true);

  foreach ($containers as $c) {
    $name = preg_replace(',^/,', '', $c['Name']);
    $ports = null;
    if ($c['NetworkSettings']['Ports']) {
      foreach ($c['NetworkSettings']['Ports'] as $ps) {
        if (isset($ps))
          foreach ($ps as $p) {
            if (isset($p['HostPort']))
              if (isset($ports)) $ports .= ", ".$p['HostPort'];
              else $ports = $p['HostPort'];
          }
      }
    } elseif ($c['HostConfig']['PortBindings']) {
      foreach ($c['HostConfig']['PortBindings'] as $ps) {
        if (isset($ps))
          foreach ($ps as $p) {
            if (isset($p['HostPort']))
              if (isset($ports)) $ports .= ", ".$p['HostPort'];
              else $ports = $p['HostPort'];
          }
      }
    }
    $attrs=$name.'\\n'.$c['Config']['Image'].'",URL="javascript:details('."'".$c['Id']."'".')",style=filled';
    if (isset($ports)) $attrs = $ports.'\\n'.$attrs.',peripheries=2';
    if ($c['State']['Dead']) $attrs.=',fillcolor=red';
    elseif ($c['State']['Restarting']) $attrs.=',fillcolor=lightblue';
    elseif ($c['State']['Paused']) $attrs.=',fillcolor=lightgrey';
    elseif ($c['State']['Running']) $attrs.=',fillcolor=lightgreen';
    else $attrs.=',fillcolor=firebrick1';
    echo '"'.$name.'" [label="'.$attrs.'];'."\n";
  }

  echo "  {rank=same;\n";
  foreach ($containers as $c) {
    if (isset($c['Volumes'])) foreach ($c['Volumes'] as $in => $out) {
      echo '        "'.$in.':'.$out.'" [label="'.$in.'";shape=box];',"\n";
    }
  }
  echo "    };\n";

  echo "  {rank=same;\n";
  foreach ($containers as $c) {
    if (isset($c['Volumes'])) foreach ($c['Volumes'] as $in => $out) {
      if (!preg_match(',^/var/lib/docker/,', $out))
        echo '      "'.$out.'" [shape=box];',"\n";
    }
  }
  echo "    };\n";

  foreach ($containers as $c) {
    if (isset($c['Volumes'])) foreach ($c['Volumes'] as $in => $out) {
      if (!preg_match(',^/var/lib/docker/,', $out))
        echo '        "'.$in.':'.$out.'" -> "'.$out.'";',"\n";
    }
  }

  foreach ($containers as $c) {
    $name = preg_replace(',^/,', '', $c['Name']);
    if (isset($c['HostConfig']['Links']))
      foreach ($c['HostConfig']['Links'] as $l) {
        $to = preg_replace(',^/?([^:]*).*$,', '${1}', $l);
        $link = preg_replace(',.*:/?'.$name.'/,', '', $l);
        echo '"'.$name.'" -> "'.$to.'" [label="'.$link.'"];'."\n";
      }
    if (isset($c['Volumes'])) foreach ($c['Volumes'] as $in => $out) {
      echo '"'.$name.'" -> "'.$in.':'.$out.'";',"\n";        
    }
  }
} else {
  echo '  A [label="Error\nCannot Inspect Docker Container"];';
  return;
}

?>