#!/usr/bin/env sh

# Abort push when the test database is unreachable, so broken code never
# reaches CI. Test DB settings come from phpunit.xml.
php -r '
$xml = @simplexml_load_file("phpunit.xml");
if ($xml === false) {
    fwrite(STDERR, "phpunit.xml not found — aborting pre-push.\n");
    exit(1);
}

$defaults = ["DB_HOST" => "127.0.0.1", "DB_PORT" => "5432", "DB_DATABASE" => "amare_test", "DB_USERNAME" => "amare", "DB_PASSWORD" => "secret"];
$env = [];
foreach ($xml->php->env as $node) {
    $name = (string) $node["name"];
    if (isset($defaults[$name])) {
        $env[$name] = (string) $node["value"];
    }
}
$config = array_merge($defaults, $env);

$dsn = sprintf("pgsql:host=%s;port=%s;dbname=%s", $config["DB_HOST"], $config["DB_PORT"], $config["DB_DATABASE"]);
try {
    new PDO($dsn, $config["DB_USERNAME"], $config["DB_PASSWORD"], [PDO::ATTR_TIMEOUT => 3]);
} catch (PDOException $e) {
    fwrite(STDERR, "\033[31mPostgreSQL is unreachable on {$config["DB_HOST"]}:{$config["DB_PORT"]} (db: {$config["DB_DATABASE"]}).\033[0m\n");
    fwrite(STDERR, "Start it with: docker compose up -d postgres\n");
    fwrite(STDERR, "Then retry the push.\n");
    exit(1);
}
' || exit 1

composer test:unit && composer test:feature
