#!/usr/bin/env bash
set -euo pipefail

SCRIPT_PATH=${BASH_SOURCE[0]}
while [[ -L "$SCRIPT_PATH" ]]; do
	SCRIPT_PARENT=$(cd "$(dirname "$SCRIPT_PATH")" && pwd -P)
	SCRIPT_TARGET=$(readlink "$SCRIPT_PATH")
	if [[ "$SCRIPT_TARGET" == /* ]]; then
		SCRIPT_PATH=$SCRIPT_TARGET
	else
		SCRIPT_PATH=$SCRIPT_PARENT/$SCRIPT_TARGET
	fi
done
SCRIPT_DIR=$(cd "$(dirname "$SCRIPT_PATH")" && pwd -P)
AUTOLOAD=$SCRIPT_DIR/../vendor/autoload.php
if [[ ! -r "$AUTOLOAD" ]]; then
	AUTOLOAD=$SCRIPT_DIR/../autoload.php
fi
if [[ ! -r "$AUTOLOAD" ]]; then
	AUTOLOAD=$SCRIPT_DIR/../../../autoload.php
fi
if [[ ! -r "$AUTOLOAD" ]]; then
	printf 'container-tools: Composer autoloader not found\n' >&2
	exit 1
fi

CONTAINER_TOOLS_AUTOLOAD=$AUTOLOAD exec php -r '
require getenv("CONTAINER_TOOLS_AUTOLOAD");
$arguments = array_slice($argv, 1);
$connection = null;
for ($i = 0; $i < count($arguments); $i++) {
    if ($arguments[$i] === "--") {
        break;
    }
    if ($arguments[$i] === "--connection" || $arguments[$i] === "-c") {
        if (!isset($arguments[$i + 1]) || str_starts_with($arguments[$i + 1], "--")) {
            fwrite(STDERR, "container-tools: {$arguments[$i]} requires a name\n");
            exit(2);
        }
        $connection = $arguments[$i + 1];
        array_splice($arguments, $i, 2);
        $i--;
        continue;
    }
    if (str_starts_with($arguments[$i], "--connection=")) {
        $connection = substr($arguments[$i], strlen("--connection="));
        if ($connection === "") {
            fwrite(STDERR, "container-tools: --connection requires a name\n");
            exit(2);
        }
        array_splice($arguments, $i, 1);
        $i--;
        continue;
    }
    if (str_starts_with($arguments[$i], "-c=")) {
        $connection = substr($arguments[$i], 3);
        if ($connection === "") {
            fwrite(STDERR, "container-tools: -c requires a name\n");
            exit(2);
        }
        array_splice($arguments, $i, 1);
        $i--;
    }
}
$manager = new \Magicoli\ContainerTools\Container\Driver\Podman($connection);
exit((new \Magicoli\ContainerTools\Console\ContainerToolsCommand($manager))->run($arguments));
' -- "$@"
