#!/usr/bin/env php
<?php
/**
 * Create zftool.phar
 * 
 * @link      http://github.com/zendframework/ZFTool for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

$srcRoot   = dirname(__DIR__);
$buildRoot = __DIR__ ;
$filename  = 'zftool.phar';

if (!file_exists("$srcRoot/vendor")) {
    echo "Error: to compile the PHAR file you need to execute composer install inside the ZFTool module\n";
    exit();
}

if (file_exists($buildRoot . "/$filename")) {
    unlink($buildRoot . "/$filename");
}

$pharPath = $buildRoot . "/$filename";
$phar = new \Phar($pharPath, 0, $filename);
$phar->startBuffering();

// remove the first line in zf.php
$phar->addFromString('zf.php', substr(php_strip_whitespace("$srcRoot/zf.php"), 19));
$phar->addFromString('Module.php', php_strip_whitespace("$srcRoot/Module.php"));

addDir($phar, "$srcRoot/vendor", $srcRoot);
addDir($phar, "$srcRoot/config", $srcRoot);
addDir($phar, "$srcRoot/src", $srcRoot);
addDir($phar, "$srcRoot/view", $srcRoot);

$stub = <<<EOF
#!/usr/bin/env php
<?php
/*
 * This file is part of ZFTool command line tool
 *
 * @link      http://github.com/zendframework/ZFTool for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
Phar::mapPhar('$filename');
require 'phar://$filename/zf.php';
__HALT_COMPILER();

EOF;

$phar->setStub($stub);
$phar->stopBuffering();

if (file_exists($pharPath)) {
    echo "Phar created successfully in $pharPath\n";
    chmod($pharPath, 0755);
} else {
    echo "Error during the compile of the Phar file $pharPath\n";
    exit(2);
}

/**
 * Add a directory in phar removing whitespaces from PHP source code
 * 
 * @param Phar $phar
 * @param string $sDir 
 */
function addDir($phar, $sDir, $baseDir = null) {
    $oDir = new RecursiveIteratorIterator (
        new RecursiveDirectoryIterator ($sDir),
        RecursiveIteratorIterator::SELF_FIRST
    );

    foreach ($oDir as $sFile) {
        if (preg_match ('/\\.php$/i', $sFile)) {
            addFile($phar, $sFile, $baseDir);
        }
    }
}

/**
 * Add a file in phar removing whitespaces from the file
 * 
 * @param Phar $phar
 * @param string $sFile 
 */
function addFile($phar, $sFile, $baseDir = null) {
    if (null !== $baseDir) {
        $phar->addFromString(substr($sFile, strlen($baseDir) + 1), php_strip_whitespace($sFile));
    } else {
        $phar->addFromString($sFile, php_strip_whitespace($sFile));
    }
}
