#!/usr/bin/env php
<?php

// Robust autoload resolver for:
// 1) installed package: /host/vendor/boru/dweb/bin/dweb -> /host/vendor/autoload.php
// 2) package dev repo:  /repo/bin/dweb -> /repo/vendor/autoload.php
$autoloadCandidates = array(
    // Installed in another project
    __DIR__ . '/../../../autoload.php',        // /host/vendor/autoload.php
    __DIR__ . '/../../../../autoload.php',     // safety (nested vendor scenarios)

    // Running inside the package repo
    __DIR__ . '/../vendor/autoload.php',
);

$autoload = null;
foreach ($autoloadCandidates as $cand) {
    if (file_exists($cand)) {
        $autoload = $cand;
        break;
    }
}

if (!$autoload) {
    fwrite(STDERR, "ERROR: Could not locate composer autoload.php\n");
    foreach ($autoloadCandidates as $cand) {
        fwrite(STDERR, "  tried: {$cand}\n");
    }
    exit(1);
}

require $autoload;

use boru\dweb\Cli\App;

try {
    $app = new App();
    exit($app->run($argv));
} catch (\Exception $e) {
    fwrite(STDERR, "ERROR: " . $e->getMessage() . "\n");
    exit(1);
}
