#!/usr/bin/env php
<?php
include dirname(__DIR__) . '/functions.inc.php';

function minify($c) {
  $minified = preg_replace('#^\s*//.+$#m', "", $c);
  $ptrn1 = <<<'EOS'
(?sx)
# quotes
(
"(?:[^"\\]++|\\.)*+"
| '(?:[^'\\]++|\\.)*+'
)
|
# comments
/\* (?> .*? \*/ )
EOS;

    $ptrn2 = <<<'EOS'
(?six)
# quotes
(
"(?:[^"\\]++|\\.)*+"
| '(?:[^'\\]++|\\.)*+'
)
|
# ; before } (and the spaces after it while we're here)
\s*+ ; \s*+ ( } ) \s*+
|
# all spaces around meta chars/operators
\s*+ ( [*$~^|]?+= | [{};,>~+-] | !important\b ) \s*+
|
# spaces right of ( [ :
( [[(:] ) \s++
|
# spaces left of ) ]
\s++ ( [])] )
|
# spaces left (and right) of :
\s++ ( : ) \s*+
# but not in selectors: not followed by a {
(?!
(?>
    [^{}"']++
| "(?:[^"\\]++|\\.)*+"
| '(?:[^'\\]++|\\.)*+' 
)*+
{
)
|
# spaces at beginning/end of string
^ \s++ | \s++ \z
|
# double spaces to single
(\s)\s+
EOS;
  $minified = preg_replace("%$ptrn1%", '$1', $minified);
  $minified = preg_replace("%$ptrn2%", '$1$2$3$4$5$6$7', $minified);
  return $minified;
} // minify()

function main($argv) {
  global $options;
  array_shift($argv);
  $src = array_shift($argv);
  $tgt = array_shift($argv);

  $options = [
    '--suffix' => '',
    '--filetypes' => false,
    '--verbose' => false,
    '--create-tree' => true,
  ];
  foreach ($argv as $pn) {
    $parts = explode('=', $pn);
    $pn = trim($parts[0]);
    if (in_array($pn, array_keys($options))) {
      $options[$pn] = (isset($parts[1]) ? trim($parts[1]) : true);

      if ($pn === '--filetypes') {
        $x = explode(',', $options['--filetypes']);
        if (count($x) > 0) {
          $options['--filetypes'] = $x;
        }
      }
    }
  }
  
  $autoloadCandidates = [
    __DIR__.'/../../../autoload.php',
    __DIR__.'/../vendor/autoload.php',
  ];
  $ready = false;
  foreach ($autoloadCandidates as $autoload) {
    if (is_readable($autoload)) {
      include $autoload;
      $ready = true;
      verbose("Using autoload: {$autoload}\n");
      break;
    }
  }
  if (!$ready) {
    terminate('Unable to find autoload.php');
  }
  
  $files = scandir($src);
  foreach ($files as $inputFile) {
    if (substr($inputFile, 0, 2) === '__') continue;
    $fullSourceFile = "{$src}/{$inputFile}";
    if (in_array($inputFile, ['.', '..']) || is_dir($fullSourceFile)) continue;
    if (is_readable($fullSourceFile)) {
      $ext = pathinfo($inputFile, PATHINFO_EXTENSION);

      if (is_array($options['--filetypes'])
        && !in_array($ext, $options['--filetypes'])
      ) {
        continue;
      } else {
        $bext = pathinfo($inputFile, PATHINFO_FILENAME);
        $outputBaseName = "{$bext}{$options['--suffix']}.{$ext}";
        if (!is_dir($tgt) && isset($options['--create-tree'])) {
          mkdir($tgt, 0755, true);
        }
        $fullOutputFile = "{$tgt}/{$outputBaseName}";
        verbose("\tMinifying: {$inputFile} as {$outputBaseName}...\n");
        try {
          $content = file_get_contents($fullSourceFile);
          $minifiedContent = minify($content);
          file_put_contents($fullOutputFile, $minifiedContent);
        } catch (\Exception $e) {
          verbose("\t{$e->getMessage()}. Ignoring.\n");
        }
      }
    }
  }
} // main

$options = [];
main($argv);
