#!/usr/bin/env php
<?php
function main($argv) {
  array_shift($argv);
  $specsFileName = array_shift($argv);

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

  $options = [
    '--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);
  }

  $autoloadCandidates = [
    __DIR__.'/../../../autoload.php',
    __DIR__.'/../vendor/autoload.php',
  ];
  $ready = false;
  foreach ($autoloadCandidates as $autoload) {
    if (is_readable($autoload)) {
      include $autoload;
      $ready = true;
      if ($options['--verbose'] === true) {
        echo "Using autoload: {$autoload}\n";
      }
      break;
    }
  }
  if (!$ready) {
    throw new \Exception('Unable to find autoload.php');
  }

  foreach ($specs as $specs) {
    $src = $specs['src'];
    $tgt = $specs['dest'];
    if (substr($tgt, -1) !== '/') {
      $tgt .= '/';
    }
    if (!is_dir($tgt)) {
      mkdir($tgt, 0777, true);
    }
    $rename = isset($specs['rename']) ? $specs['rename'] : false;
    try {
      if (is_file($src)) {
        $srcName = basename($src);
        $destName = $srcName;
        if ($rename !== false) {
          $destName = $rename;
        }
        if ($options['--verbose'] === true) {
          echo "Copy {$src} ==> {$tgt}{$destName}\n";
        }
        copy($src, "{$tgt}{$destName}");
        if ($options['--verbose'] === true) {
          echo "\tOK\n";
        }
      } elseif (is_dir($src)) {
        if (substr($src, -1) !== '/') {
          $src .= '/';
        }
        $dir = scandir($src);
        foreach ($dir as $srcName) {
          if (in_array($srcName, ['.', '..'])) continue;
          $destName = $srcName;
          if ($rename !== false) {
            $destName = $rename;
          }
          $fullSrc = "{$src}{$srcName}";
          $fullTgt = "{$tgt}{$destName}";
          if (is_readable($fullSrc)) {
            if ($options['--verbose'] === true) {
              echo "Copy {$fullSrc} ==> {$fullTgt}\n";
            }
            copy($fullSrc, $fullTgt);
            if ($options['--verbose'] === true) {
              echo "\tOK\n";
            }
          }
        }
      } else {
        throw new \Exception('Invalid settings');
      }
    } catch(\Exception $e) {
      if ($options['--verbose'] === true) {
        echo "\tfailed\n";
      }
    }
  }
} // main

main($argv);
