#!/usr/bin/env php
<?php /** @since 1.2.1 */
global $version;
echo "version: " . ($version = json_decode(file_get_contents(__DIR__ . "/../composer.json"), true)["version"]) . PHP_EOL;

switch ($argv[1] ?? '') {
    case '--normal':
    case '':
        build();
        break;
    case '--help':
    case '-h':
    default:
        echo "\nzhamao-framework Phar builder.\n";
        echo "\nUsage: " . $argv[0] . " [OPTION]";
        echo "\n\n  -h, --help\t\tShow this help menu";
        echo "\n  --with-wechat-patch\tReplace ModBase with wechat patch version and build your own phar package";
        echo "\n  --normal\t\tBuild your own phar package as normal options\n\n";
        break;
}

function build($with_wechat_patch = false) {
    if (ini_get('phar.readonly') == 1) {
        die("You need to set \"phar.readonly\" to \"Off\"!\nSee: https://stackoverflow.com/questions/34667606/cant-enable-phar-writing\n");
    }
    $filename = "server.phar";
    @unlink(__DIR__ . '/../resources/' . $filename);
    $phar = new Phar(__DIR__ . '/../resources/' . $filename);
    $phar->startBuffering();
    $src = realpath(__DIR__ . '/../');
    $hello = file_get_contents($src . '/src/Module/Example/Hello.php');
    $middleware = file_get_contents($src . '/src/Module/Middleware/TimerMiddleware.php');
    unlink($src . '/src/Module/Example/Hello.php');
    unlink($src . '/src/Module/Middleware/TimerMiddleware.php');
    if ($with_wechat_patch) {
        global $wechat_patch;
        $wechat = base64_decode($wechat_patch);
    } else {
        $wechat = false;
    }
    if ($wechat !== false) {
        echo "Using wechat patch.\n";
        $modbase = file_get_contents($src . '/src/ZM/ModBase.php');
        unlink($src . '/src/ZM/ModBase.php');
    }
    $phar->buildFromDirectory($src);
    $phar->addFromString('tmp/Hello.php.bak', $hello);
    $phar->addFromString('tmp/TimerMiddleware.php.bak', $middleware);
    if ($wechat !== false) {
        $phar->addFromString('src/ZM/ModBase.php', $wechat);
        file_put_contents($src . '/src/ZM/ModBase.php', $modbase);
    }
    //$phar->compressFiles(Phar::GZ);
    $phar->setStub($phar->createDefaultStub('phar-starter.php'));
    $phar->stopBuffering();
    file_put_contents($src . '/src/Module/Example/Hello.php', $hello);
    file_put_contents($src . '/src/Module/Middleware/TimerMiddleware.php', $middleware);
    echo "Successfully built. Location: " . $src . "/resources/$filename\n";
}

