#!/usr/bin/env bash
# Test: set-repository-url.sh writes CLUSEV_REPOSITORY (derived from the clone origin) into the .env,
# creating or replacing the line, and strips a trailing .git.
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
work="$(mktemp -d)"; trap 'rm -rf "$work"' EXIT

git init -q "$work/proj"
git -C "$work/proj" remote add origin https://git.example.com/o/clusev.git
printf 'APP_ENV=local\n' > "$work/proj/.env"

bash "$here/set-repository-url.sh" "$work/proj" "$work/proj/.env"
grep -qx 'CLUSEV_REPOSITORY=https://git.example.com/o/clusev' "$work/proj/.env" || { echo "FAIL: append/strip-.git"; exit 1; }

# replace an existing line
printf 'CLUSEV_REPOSITORY=old\n' >> "$work/proj/.env"
git -C "$work/proj" remote set-url origin https://selfhosted.local/u/clusev
bash "$here/set-repository-url.sh" "$work/proj" "$work/proj/.env"
test "$(grep -c '^CLUSEV_REPOSITORY=' "$work/proj/.env")" = 1 || { echo "FAIL: duplicate line"; exit 1; }
grep -qx 'CLUSEV_REPOSITORY=https://selfhosted.local/u/clusev' "$work/proj/.env" || { echo "FAIL: replace"; exit 1; }

# no origin → no-op, no crash
git init -q "$work/noremote"; printf '' > "$work/noremote/.env"
bash "$here/set-repository-url.sh" "$work/noremote" "$work/noremote/.env"
grep -q 'CLUSEV_REPOSITORY' "$work/noremote/.env" && { echo "FAIL: wrote without origin"; exit 1; }

echo "PASS"
