<?php

$cwd = dirname($argv[0]) . "/../../../src";
chdir($cwd);

$cmd = "grep -r -l 'Generated by the protocol buffer' * | grep 'php$' | grep -v Internal";
$handle = popen($cmd, 'r');
$filenames = explode("\n", stream_get_contents($handle));
array_pop($filenames);  // empty string after last '\n'
$filenames[] = "Google/Protobuf/DescriptorPool.php";
$output = "../ext/google/protobuf/bundled_php.c";

function stripSuffix($str, $suffix) {
  return substr($str, 0, strlen($str) - strlen($suffix));
}

function toClassName($filename) {
  # Google/Protobuf/BoolValue.php -> Google\\Protobuf\\BoolValue
  $ret = stripSuffix($filename, ".php");
  return str_replace("/", "\\\\", $ret);
}

function toCSymbolName($filename) {
  # Google/Protobuf/BoolValue.php -> Google__Protobuf__BoolValue
  $ret = stripSuffix($filename, ".php");
  return str_replace("/", "__", $ret);
}

$f = fopen($output, "w");

fwrite($f, "#include \"bundled_php.h\"\n");
fwrite($f, "#include \"stdlib.h\"\n");

foreach ($filenames as $filename) {
  print("Reading $filename...\n");
  $contents = file_get_contents($filename);
  $contents = substr($contents, 5);  // Strip <?php
  $c_symbol_name = toCSymbolName($filename);
  fwrite($f, "static const char {$c_symbol_name}[] = {");
  for ($i = 0; $i < strlen($contents); $i++) {
    if ($i % 10 == 0) {
      fwrite($f, "\n");
    }
    fprintf($f, "  0x%02x,", ord($contents[$i]));
  }
  fwrite($f, "0};\n");
}

fwrite($f, "static BundledPhp_File php[] = {\n");
foreach ($filenames as $filename) {
  $class_name = toClassName($filename);
  $c_symbol_name = toCSymbolName($filename);
  fwrite($f, "  {\"$class_name\", $c_symbol_name},\n");
}

fwrite($f, "  {NULL, NULL}\n");
fwrite($f, "};\n");
fwrite($f, "BundledPhp_File *bundled_files = &php[0];\n");
fclose($f);

print("Wrote $output\n");
?>
