#!/usr/bin/env php
<?php

foreach ([__DIR__.'/../../../autoload.php', __DIR__.'/../vendor/autoload.php'] as $file) {
    if (file_exists($file)) {
        require_once $file;
        break;
    }
}


function transformCode($codemodPaths, $srcPath, $outPath, $ignorePaths) {
    try {
        $oRunner = new \Codeshift\CodemodRunner();
        $oRunner->addCodemods($codemodPaths);
        $oRunner->executeSecured($srcPath, $outPath, $ignorePaths);
    }
    catch (\Exception $ex) {
        die("\nFatal Error!\n{$ex->getMessage()}\n");
    }
}

function dumpFileAST($filePath, $outputPath=null) {
    try {
        $oTransformer = new \Codeshift\CodeTransformer();
        $astPrint = $oTransformer->dumpFileAST($filePath, $outputPath);

        if (!$outputPath) {
            echo $astPrint;
        }
    }
    catch (\Exception $ex) {
        die("\nFatal Error!\n{$ex->getMessage()}\n");
    }
}


// Process command-line arguments
$optionsMap = getopt('', ['help', 'ast:', 'mod:', 'src:', 'out:', 'ignore:']);

if (isset($optionsMap['help'])) {
    echo "\n";
    echo "Usage:\n";
    echo "  codeshift [options]\n";
    echo "\n";
    echo "Options (equal signs can be omitted):\n";
    echo "  --help              Print this help.\n";
    echo "  --ast=<path>        Full path of a file to create the AST for.\n";
    echo "  --mod=<path>        Full path of a codemod file to execute.\n";
    echo "  --src=<path>        Full path of a file or directory to run the codemod on.\n";
    echo "  --out=<path>        Optional full path of a file or directory to write the results to.\n";
    echo "  --ignore=<paths>    Optional comma-separated list of paths to ignore on directory traversing.\n";
    echo "                      Relative paths are resolved based on src path.\n";
    echo "\n";
    echo "Example to transform code:\n";
    echo "  codeshift --mod=/my/codemod.php --src=/my/code/dir\n";
    echo "\n";
    echo "Example to print ast:\n";
    echo "  codeshift --ast=/my/code/file.php --out=/my/output.txt\n";
    echo "\n";
}
elseif (isset($optionsMap['mod']) AND isset($optionsMap['src'])) {
    $codemodPath = $optionsMap['mod'];
    $srcPath = $optionsMap['src'];
    $outPath = (isset($optionsMap['out']) ? $optionsMap['out'] : null);
    $ignorePaths = (isset($optionsMap['ignore']) ? explode(',', $optionsMap['ignore']) : []);

    transformCode([$codemodPath], $srcPath, $outPath, $ignorePaths);
}
elseif (isset($optionsMap['ast'])) {
    dumpFileAST($optionsMap['ast'], $optionsMap['out']);
}
else {
    die('Nothing to do, see --help'."\n");
}


