#!/bin/env php
<?php

require("inc_vars.php");
require("inc_functions.php");

$INFILE="$selfdir/src/amcli.php";
$INCFILE="$selfdir/src/include_checks.php";
$TMPFILE="$selfdir/$dirBuild/amcli.php.tmp";

$OUTFILE="$selfdir/$dirPackages/".str_replace('.php', '', basename($INFILE)).$myosextension;
$OUTFILE2="$selfdir/$dirPackages/".str_replace('.php', '', basename($INFILE)).'_'.$myos.'_'.$myarchitecture.$myosextension;

$FLAG_FORCEBUILD=false;
$FLAG_FULLTEST=false;

echo "
  \e[1mCLI client\e[0m
  DEVELOPMENT ENVIRONMENT

  B U I L D E R

...............................................................................
";

if ($argc > 1) {
    parse_str(implode('&', array_slice($argv, 1)), $ARGS);
}

if(isset($ARGS['-h']) || isset($ARGS['--help'])){
    echo "
    - Merge PHP sources to a single file
    - Compile binary
    - Test binary
    - Coy to architecture specific binary
    - Create readme with buildinfos

...............................................................................

 ✨ \e[1mSYNTAX:\e[0m

    ./build.php [OPTIONS]

 🔷 \e[1mOPTIONS:\e[0m

    -h, --help     Show this help
    -f, --force    Force rebuild on unchanged sources
    -t, --test     Run full test suite: ./tests/00_start.php
                   without '-t': run a  single check only.

";
    exit(0);
}

if(isset($ARGS['-f']) || isset($ARGS['--force'])){
    $FLAG_FORCEBUILD=true;
}
if(isset($ARGS['-t']) || isset($ARGS['--test'])){
    $FLAG_FULLTEST=true;
}

_h1("Startup");
_chdir($selfdir);
_mkdir($dirPackages);

// ----------------------------------------------------------------------

_h1("Check target file");
if(file_exists($OUTFILE)){
    $ts_in=filemtime($INFILE);
    $ts_out=filemtime($OUTFILE);
    if($ts_in>$ts_out){
        echo "✅ INFO: Source file \"$INFILE\" is newer than \"$OUTFILE\". Compiling changes...\n";
    } else {
        if($FLAG_FORCEBUILD){
            echo "🔹 INFO: Source is unchanged since last build... rebuilding it because of --force param.\n";
        } else{
            echo "Source is unchanged since last build. \n   Delete \"$OUTFILE\"\n   or use --force to force a rebuild.\n";
            _abort("Aborting.");
        }
    }
} else {
    echo "✅ INFO: Target \"$OUTFILE\" does not exist yet.\n";
}

// ----------------------------------------------------------------------

_h1("Prepare source");
$sBuildDate=date("Y-m-d H:i:s");
$sBuildPhpcode="\$AMCLI_BUILD_DATE=\"$sBuildDate\";";
$datefile=str_replace('.php', '__build.php', $INFILE);
file_put_contents(
    $datefile, "<?php
        // This file was generated by ".__FILE__."
        $sBuildPhpcode"
);
$in=file_get_contents($INFILE);
$inccode=$sBuildPhpcode . "\n". file_get_contents($INCFILE);
$inccode=str_replace("<?php", "", $inccode);

$tempcode=preg_replace("#\/\/ ---MARK---INCLUDE-CHECKS---START---.*---MARK---INCLUDE-CHECKS---END#s", "$inccode", $in);

if(file_put_contents($TMPFILE, $tempcode)){
    _ok("$TMPFILE was written");
}

// ----------------------------------------------------------------------

_h1("Compile");
_chdir("$selfdir/$dirBuild");
_exec("$SPC \
    micro:combine \
    \"$TMPFILE\" \
    -O \"$OUTFILE\"");

// if(unlink($TMPFILE)){
//     echo "Cleanup: $TMPFILE was deleted\n";
// }

// ----------------------------------------------------------------------

_h1("Test generated binary");


if ($FLAG_FULLTEST){
    _h1("Run test suite");
    _exec("php \"$selfdir/tests/00_start.php\" --bin \"$OUTFILE\"");
} else {
    _skip("don't run test suite. Use --test to run it. Starting simple test.");
    _exec("file \"$OUTFILE\"");
    _exec("\"$OUTFILE\" --ini=../tests/configs/metadata.ini");
    }

_h1("Write architecture specific binary");
if(!copy($OUTFILE, $OUTFILE2)){
    _abort("Could not copy $OUTFILE to $OUTFILE2");
}
_ok("file created: '$OUTFILE2'");
_exec("chmod +x $OUTFILE2");

_h1("Create readme");
$readme="{$OUTFILE2}__README.md";
$versionSPC=system("$SPC --version");

$versionAmcli=system("php $INFILE --version");

if (!file_put_contents($readme, 
    "# Build infos $versionAmcli

Date        : $sBuildDate

OS          : $myos
architecture: $myarchitecture

File        : ".basename($OUTFILE2)."

## Versions

Used SPC    : $versionSPC
PHP version : $php_version
PHP modules : $php_libs

## Conmands

Download    : `$cmdSpcDownload`

Build       : `$cmdSpcBuild`

see https://os-docs.iml.unibe.ch/appmonitor-cli-client/
")){
    _abort("Could not write $readme");
}
_ok("file created.");


// ----------------------------------------------------------------------
@include "build_postactions.php";

_h1("Summary");
echo "The created files are:

- $OUTFILE
- $OUTFILE2
- $readme
";

_h1("Build was successful.");

// ----------------------------------------------------------------------