<?php

$format = $argv[1];
$output = $argv[2];
$files = array_slice($argv, 3);

($f = fopen($output, 'w')) || die("cannot open $output");

$FORMAT = strtoupper($format);

fwrite($f, "\n/* Generated by idl_list.php from $files. Do NOT modify. */\n\n");

switch ($format) {
case 'ext':
  fwrite($f, <<<EOT

#ifndef incl_EXT_LIST_{$FORMAT}_H_
#define incl_EXT_LIST_{$FORMAT}_H_


EOT
  );
  break;
}

sort($files);
foreach ($files as $file) {
  // Find the common prefix of our current path (which is
  // $SOMETHING/hphp/idl) and whatever is on our command line
  // (typically EXT= and FIND_IDL, both from make).  From here we know
  // the prefix to use when constructing our #include's.
  $file = realpath($file);
  $cwd = realpath(getcwd()) . "/";
  for ($i = strlen($cwd); $i >= 0; --$i) {
    if (strncmp($cwd, $file, $i) === 0) {
      $file = substr($file, $i);
      break;
    }
  }
  // Separate bar/quux/blah.idl.json into $prefix (bar/quux) and $name
  // (blah) for generating the includes below.  If a prefix can't be
  // determined, we assume it is under runtime/ext.
  preg_match('%^(.*/)?(.*)\.idl\.json$%', $file, $matches);
  $prefix = $matches[1];
  $name = $matches[2];
  $ucname = $prefix ? camelCase($name) : ucfirst($name);

  if ($name === 'constants') {
    // Ignore 'cosntants.idl.json'
    continue;
  }

  switch ($format) {
  case 'ext':
    $path = $prefix ? "hphp/$prefix" : "hphp/runtime/ext/";
    fwrite($f, "#include \"${path}ext_$name.h\"\n");
    break;
  }
}

switch ($format) {
case 'ext':
  fwrite($f, <<<EOT

#endif // incl_EXT_LIST_{$FORMAT}_H_

EOT
  );
  break;
}

fclose($f);

function camelCase($name) {
  $names = explode('_', $name);
  return implode(array_map("ucfirst", $names));
}
