<?php
/**
 * Webasyst Framework Download & Install
 *
 * Zero-dependency single-file script. Use in CLI (no args) or open in browser.
 * Downloads the archive and extracts it, then hands off to the standard install.php flow.
 *
 * Usage:
 *   `php -r "echo file_get_contents('https://www.webasyst.com/webasyst.php');" | php`
 *   (or) `php webasyst.php & rm webasyst.php`
 *   (or) download this file, place in target web-server directory, open in browser
 */

define('WA_MIN_PHP_VERSION', '8.2.0');
define('WA_DOWNLOAD_URL', 'https://www.webasyst.com/download/framework/');

error_reporting(E_ALL);
@set_time_limit(599);
@ini_set('memory_limit', '512M');

// Step 1: Version check
if (version_compare(PHP_VERSION, WA_MIN_PHP_VERSION, '<')) {
    fail("Webasyst requires PHP " . WA_MIN_PHP_VERSION . " or higher. Your version: " . PHP_VERSION);
}

$isCli   = (PHP_SAPI === 'cli');
$isWin   = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
$target  = getcwd();

// if by any chance framework is already installed, abort
if (class_exists('waSystem')) {
    return; // just load functions, used for testing
}
if (file_exists($target.'/wa-config/SystemConfig.class.php')) {
    fail("Webasyst is already installed.");
}

// Step 2: ensure dependencies
if (!function_exists('curl_init')) {
    fail('Download failed: curl is not available.');
}
$extractor = null;
if (class_exists('Archive_Tar')) {
    $extractor = 'archive_tar';
} elseif (class_exists('PharData') && extension_loaded('zlib')) {
    $extractor = 'phar';
} elseif (function_exists('shell_exec') && !$isWin) {
    // Check if shell_exec is not in disabled_functions
    $disabled = array_map('trim', explode(',', ini_get('disable_functions')));
    if (!in_array('shell_exec', $disabled)) {
        $test = shell_exec('command -v tar 2>/dev/null || which tar 2>/dev/null');
        if (!empty(trim($test ?? ''))) {
            $extractor = 'tar';
        }
    }
}
if (!$extractor) {
    fail('No archive extractor available: need Archive_Tar, PharData (with zlib), or system tar.');
}

// Render spinner for the web, then start actual work after redirect to ?run=1
if (!$isCli && empty($_GET['run'])) {
    ?><!DOCTYPE html><style>
body { padding: 12px; }
.spinner {
    width: 24px;
    height: 24px;
    border: 5px solid #ddd;
    border-top-color: #2049B3;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
<div class="spinner"></div>
<div style="font-style: italic; margin-top: 10px;">
    Downloading Webasyst...<br>
    <span style="color: #aaa;"><?php
 echo WA_DOWNLOAD_URL; ?></span>
</div>
<script>window.location="?run=1";</script><?php
    exit;
}

// global used in CLI progress rendering
$progressLastLen = 0;

$tmpGz = $target . '/.wa_download_' . uniqid() . '.tar.gz';

try {
    // Step 3: Download
    download(WA_DOWNLOAD_URL, $tmpGz);

    // Step 4: Extract
    extractArchive($tmpGz, $extractor);

    // Step 5: Fix permissions
    fixPermissions($target);

    // Step 6: Cleanup & handoff
    @unlink($tmpGz);
    handoff();
    exit;
} catch (\Throwable $e) {
    @unlink($tmpGz);
    fail('Unexpected error: ' . $e->getMessage());
}

//
// Functions
//

function out(string $msg): void {
    global $isCli;
    if ($isCli) {
        echo $msg . "\n";
    }
}

function fail(string $msg, int $httpCode = 500): void {
    global $isCli;
    if ($isCli) {
        echo "\nError: " . $msg . "\n";
        exit(1);
    }
    http_response_code($httpCode);
    header('Content-Type: text/plain; charset=utf-8');
    echo $msg;
    exit;
}

/**
 * Download the archive with CLI progress bar (or silent in web).
 * Uses fopen() with stream context; falls back to curl.
 *
 * @param string $url        Download URL
 * @param string $destTmpGz  Local temp file path
 */
function download(string $url, string $destTmpGz): void {
    global $isCli;

    // Make sure .htaccess and index.php do not exist
    // (this prevents script from accidentally being run on a living site)
    if (file_exists('.htaccess') || file_exists('index.php')) {
        $message = 'Make sure .htaccess, index.php and other files in directory '.realpath('.')."\nare removed.";
        if (
            (file_exists('.htaccess') && !is_writable('.htaccess')) ||
            (file_exists('index.php') && !is_writable('index.php'))
        ) {
            $message .= 'Also check the directory permissions and ownership: script must be able to create files. For local development chmod 777 will do (avoid in production).';
        }
        fail($message);
    }

    // Open destination file
    $destFp = @fopen($destTmpGz, 'wb');
    if (!$destFp) {
        fail(
            "Cannot write to current directory ".realpath('.')."\n\n".
            "Check the directory permissions or ownership, fix with chmod or chown. For local development chmod 777 will do (avoid in production)."
        );
    }

    out("Downloading Webasyst framework from ".WA_DOWNLOAD_URL);

    try {
        $ch = curl_init($url);
        if (!$ch) {
            throw new \RuntimeException('curl_init() failed');
        }
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER  => false,
            CURLOPT_FOLLOWLOCATION  => true,
            CURLOPT_MAXREDIRS       => 5,
            CURLOPT_FILE            => $destFp,
            CURLOPT_CONNECTTIMEOUT  => 30,
            CURLOPT_TIMEOUT         => 600,
            CURLOPT_BUFFERSIZE      => 1048576,  // 1 MB
            CURLOPT_PROGRESSFUNCTION => function ($_, int $dlSize, int $dlNow) use ($isCli) {
                if ($isCli && $dlSize > 0) {
                    renderProgressBar($dlNow, $dlSize);
                } elseif ($isCli && $dlNow > 0) {
                    renderSpinner($dlNow);
                }
            },
            CURLOPT_NOPROGRESS       => false,
        ]);

        $result = curl_exec($ch);
        $error  = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($result === false || !empty($error)) {
            throw new \RuntimeException('cURL error: ' . $error);
        }
        if ($httpCode >= 400) {
            throw new \RuntimeException('HTTP ' . $httpCode);
        }
    } catch (\Throwable $e) {
        fclose($destFp);
        @unlink($destTmpGz);
        fail('Download failed: ' . $e->getMessage());
    }

    fclose($destFp);

    if ($isCli) {
        // Final newline after progress bar/spinner
        echo "\n";
    }

    if (!file_exists($destTmpGz) || filesize($destTmpGz) === 0) {
        @unlink($destTmpGz);
        fail('Download failed: zero-byte file.');
    }

    out("Download complete: " . round(filesize($destTmpGz) / 1048576, 1) . " MB");
}

function renderProgressBar(int $now, int $total): void {
    global $progressLastLen;
    if ($total <= 0) return;

    $pct   = min(100, (int) round(($now / $total) * 100));
    $width = 30;
    $filled = (int) round(($now / $total) * $width);
    $bar   = str_repeat('=', max(0, $filled - 1)) . ($filled > 0 ? '>' : '') . str_repeat(' ', $width - $filled);
    $nowMB  = round($now / 1048576, 1);
    $totMB  = round($total / 1048576, 1);

    $line = "\r[{$bar}] {$pct}% ({$nowMB}/{$totMB} MB)";

    // Pad or trim to clear previous line
    echo $line;
    if (strlen($line) < $progressLastLen) {
        echo str_repeat(' ', $progressLastLen - strlen($line));
    }
    $progressLastLen = strlen($line);
    flush();
}

function renderSpinner(int $now): void {
    global $progressLastLen;
    $spinners = ['|', '/', '-', '\\'];
    $idx = (int) floor($now / 1048576) % 4; // change every MB
    $line = "\rDownloading... " . $spinners[$idx] . '  ' . round($now / 1048576, 1) . ' MB';

    echo $line;
    if (strlen($line) < $progressLastLen) {
        echo str_repeat(' ', $progressLastLen - strlen($line));
    }
    $progressLastLen = strlen($line);
    flush();
}

/**
 * Extract the archive using the detected backend.
 *
 * @param string $tmpGz        Path to the .tar.gz file
 * @param string $extractor    One of 'archive_tar', 'phar', 'tar'
 */
function extractArchive(string $tmpGz, string $extractor): void {
    global $target;

    out("Using extractor: {$extractor}");

    switch ($extractor) {
        case 'archive_tar':
            $t = new Archive_Tar($tmpGz, 'gz');
            if (!$t->extract($target)) {
                throw new \RuntimeException('Archive_Tar extraction returned false');
            }
            break;

        case 'phar':
            // PharData: decompress the .gz layer to .tar, then extract.
            $tarPath = preg_replace('/\.gz$/', '', $tmpGz);  // .tar.gz -> .tar
            try {
                $pharGz = new PharData($tmpGz);
                $pharGz->decompress();                    // produces $tarPath next to source
                $pharTar = new PharData($tarPath);
                $pharTar->extractTo($target, null, true); // overwrite = true
            } finally {
                @unlink($tarPath);
            }
            break;

        case 'tar':
            $escTmpGz = escapeshellarg($tmpGz);
            $escTgt   = escapeshellarg($target);
            // Redirect stderr to stdout and capture exit code
            $output = shell_exec("tar -xzf {$escTmpGz} -C {$escTgt} 2>&1; echo \"EXIT:\$?\"");
            if ($output === null || strpos($output, 'EXIT:0') === false) {
                throw new \RuntimeException('system tar extraction failed: ' . ($output ?? 'null'));
            }
            break;
    }

    // Verify files exist on target
    if (!file_exists($target . '/install.php') || !file_exists($target . '/wa-installer/install.php')) {
        throw new \RuntimeException(
            'Extraction verification failed, some files not found in ' . $target
        );
    }

    out("Extraction complete.");
}

/** Set permissions recursively (non-Windows only). */
function fixPermissions(string $target): void {
    global $isCli, $isWin;

    if ($isWin) {
        out("Skipping permission fix (Windows).");
        return;
    }

    out("Fixing permissions...");

    $warnings = [];
    try {
        $it = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($target, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        );

        foreach ($it as $item) {
            $path = $item->getPathname();
            if ($item->isDir()) {
                if (!@chmod($path, 0755)) {
                    $warnings[] = "chmod 0755 failed: {$path}";
                }
            } else {
                if (!@chmod($path, 0644)) {
                    $warnings[] = "chmod 0644 failed: {$path}";
                }
            }
        }
    } catch (\Throwable $e) {
        $warnings[] = "Permission walk error: " . $e->getMessage();
    }

    // Make index.php and install.php writable
    foreach (['index.php', 'install.php'] as $f) {
        $fp = $target . '/' . $f;
        if (file_exists($fp)) {
            if (!@chmod($fp, 0666)) {
                $warnings[] = "chmod 0666 failed: {$fp}";
            }
        }
    }

    if ($warnings && $isCli) {
        foreach ($warnings as $w) {
            echo "[warn] {$w}\n";
        }
    }

    out("Permissions done.");
}

function handoff(): void {
    global $isCli;

    if ($isCli) {
        echo "\n";
        echo "============================================================\n";
        echo "                                                            \n";
        echo "   Webasyst Framework is downloaded and extracted.          \n";
        echo "                                                            \n";
        echo "   Continue by opening URL in your browser:                 \n";
        echo "                                                            \n";
        echo "   ".autodetectInstallationUrl()."                          \n";
        echo "                                                            \n";
        echo "============================================================\n";
        echo "\n";
    } else {
        // Web: self-delete, redirect to install.php
        if (file_exists(__FILE__)) {
            @unlink(__FILE__);
        }
        header('Location: install.php');
        exit;
    }
}

/** Try to figure out installation URL by looking for domain name in path */
function autodetectInstallationUrl()
{
    global $target;
    $path = str_replace('\\', '/', $target.'/install.php');
    if (!preg_match('~/(([a-z0-9]([-a-z0-9]*[a-z0-9])?\.+[a-z]{2,12})(?:/.*)?/install.php)~i', $path, $m)) {
        return 'http://youdomain.com/install.php';
    }
    $domain = $m[2];
    $candidate = $m[1];
    return 'http://'.preg_replace('~'.preg_quote($domain).'.*/(wwwroot|public|current|dist|web|ht(tps?)?docs|(public_)?html|www)/~', $domain.'/', $candidate);
}
        