<?php
//Nifty: Script to expand Apache conf with all includes
$conf = $argv[1];

if(!is_file($conf)) {
  errout("File not found: $conf");
  exit(1);
}

echo expand_includes($conf);

$server_root = false;
function expand_includes($conf) {
  global $server_root;

  $file = file($conf, FILE_IGNORE_NEW_LINES);
  $cdir = realpath(dirname($conf));

  $complete_file = "";
  foreach($file as $line) {

    if(preg_match('/^\s*serverroot\s+(\"?)([a-z0-9\/]+)/i', $line, $srm)) {
      $server_root = $srm[2];
    }

    $inc_regex = '^\s*(?!#)include(optional)?\s+\"?'."\'".'?([a-z\-\_\/\.\*]+)';
    if(preg_match("/" . $inc_regex . "/i", $line, $match)) {

      if(!$server_root) {
        die("Found first include but server_root is missing!\n");
      }

      $inc_path = $match[2];

      if(substr($inc_path, 0, 1) == "/") {
        $full_inc = $inc_path;
      } else {
        $full_inc = $server_root . "/" . $inc_path;
      }

      foreach(glob($full_inc) as $exp) {
        errout("Expanding into $exp");
        $complete_file .= PHP_EOL . PHP_EOL;
        $complete_file .= PHP_EOL . PHP_EOL;
        $complete_file .= PHP_EOL . PHP_EOL;
        $complete_file .= "#########################\n";
        $complete_file .= "## BEGIN EXPANDING $exp \n";
        $complete_file .= "#########################\n";
        $complete_file .= expand_includes($exp);
        $complete_file .= "## END EXPANDING $exp \n";
        $complete_file .= PHP_EOL . PHP_EOL;
      }

      echo PHP_EOL;
    }

    $complete_file .= $line . PHP_EOL;
  }

  return $complete_file;
}

function errout($txt) {
  fwrite(STDERR, print_r($txt, true) . PHP_EOL);
}
