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

function copyDir($src, $tgt, $recursive = false, $level = 1) {
  if (substr($src, -1) !== '/') {
    $src .= '/';
  }
  if (substr($tgt, -1) !== '/') {
    $tgt .= '/';
  }
  $dir = scandir($src);
  foreach ($dir as $srcFileName) {
    if (in_array($srcFileName, ['.', '..'])) {
      continue;
    }
    $fullSrc = "{$src}{$srcFileName}";
    $fullTgt = "{$tgt}{$srcFileName}";

    if (is_dir($fullSrc) && $recursive) {
      copyDir($fullSrc, $fullTgt, $recursive, $level+1);
    }

    $tab = str_repeat("\t", $level);
    if (is_readable($fullSrc) && !is_dir($fullSrc)) {
      if (!is_dir($tgt)) {
        verbose("\tCreate dir: {$tgt}\n");
        mkdir($tgt, 0755, true);
      }
      verbose("{$tab}Copy {$fullSrc} ==> {$fullTgt}\n");
      copy($fullSrc, $fullTgt);
      verbose("{$tab}OK\n");
    }
  }
}

function makeOptions($argv) {
  array_shift($argv);
  $specsFileName = array_shift($argv);

  if (pathinfo($specsFileName, PATHINFO_EXTENSION) !== 'json') {
    terminate("Invalid specs file, JSON expected.");
  }
  $specs = json_decode(file_get_contents($specsFileName), true);

  $options = [
    'specs' => $specs,
    '--verbose' => false,
  ];
  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 (!count($specs)) {
    if ($options['--verbose'] === true) {
      echo "No files to copy.\n";
    }
    exit(0);
  }
  return $options;
}

function main() {
  global $options;
  $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) {
    throw new \Exception('Unable to find autoload.php');
  }

  $specs = $options['specs'];
  foreach ($specs as $specs) {
    $src = $specs['src'];
    $tgt = $specs['dest'];
    $recursive = isset($specs['recursive'])
      ? boolval($specs['recursive'])
      : false;
    if (substr($tgt, -1) !== '/') {
      $tgt .= '/';
    }
    if (!is_dir($tgt)) {
      mkdir($tgt, 0755, true);
    }
    $rename = isset($specs['rename']) ? $specs['rename'] : false;
    try {
      if (is_file($src)) {
        $srcName = basename($src);
        $destName = $srcName;
        if ($rename !== false) {
          $destName = $rename;
        }
        verbose("Copy {$src} ==> {$tgt}{$destName}\n");
        copy($src, "{$tgt}{$destName}");
        verbose("OK\n");
      } elseif (is_dir($src)) {
        if ($recursive === true) {
          copyDir($src, $tgt, true);
        } else {
          copyDir($src, $tgt);
        }
      } else {
        throw new \Exception('Invalid settings');
      }
    } catch(\Exception $e) {
      verbose("\tfailed\n");
    }
  }
} // main

$options = makeOptions($argv);
main();
