#!/usr/bin/env php
<?php
/** Create the .phar for fail2banServer
*/
$pharFile = "debian/tmp/fail2banmgr-server.phar";
$srcRoot = realpath (__DIR__."/..");
chdir($srcRoot);
$startFileCLI = "router.php";
$startFileWeb = "router.php";
$exclude = array ("data/");
$compact = false;

if (file_exists ($pharFile))
  unlink ($pharFile);
$phar = new Phar ($pharFile);
$iterator = new RecursiveDirectoryIterator($srcRoot);
$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $file)
{
  $relativeFile = substr ($file, strlen ($srcRoot) + 1);
  if (basename ($relativeFile) === "." || basename ($relativeFile) === "..")
    continue;
  if (! is_file ($relativeFile))
    continue;
  foreach ($exclude as $excl)
  {
    if (substr ($excl, -1) === "/" &&
        substr ($relativeFile, 0, strlen ($excl) -1 )."/" === $excl)
      continue 2;
    if (basename (dirname ($relativeFile)) === $excl ||
        $relativeFile === $excl)
      continue 2;
  }
  if ($compact)
    $phar->addFromString ($relativeFile, php_strip_whitespace ($relativeFile));
  else
    $phar->addFromString ($relativeFile, file_get_contents ($relativeFile));
}
$tmp = tempnam ("/tmp", "stub-");
file_put_contents ($tmp, $phar->createDefaultStub ($startFileCLI,
   $startFileWeb));

if ($compact)
  $phar->setStub ("#!/usr/bin/env php\n<?php ob_clean();?>\n" . php_strip_whitespace ($tmp));
else
  $phar->setStub ("#!/usr/bin/env php\n<?php ob_clean();?>\n" . file_get_contents ($tmp));
unlink ($tmp);

$newFile = substr (basename($pharFile), 0, -5);
rename ($pharFile, $newFile);
if (file_exists ($newFile))
  echo "   File '$newFile' created\n";
else
  echo "   ERROR : Can not create '$newFile'\n";
