#!/usr/bin/env bash
# Derive the update source (CLUSEV_REPOSITORY) from the clone origin and write it into the given .env.
# Called by install.sh + update.sh. The private (upstream/mirror) URL therefore lives ONLY in the
# gitignored .env — never in a tracked file. No-op (exit 0) when there is no origin remote.
#   usage: set-repository-url.sh <project-dir> <env-file>
set -euo pipefail

proj="${1:?project dir required}"
envfile="${2:?env file required}"

url="$(git -C "$proj" remote get-url origin 2>/dev/null || true)"
# Strip any inline credentials (https://user:token@host → https://host). A clone origin may carry an
# embedded push token (the release flow uses https://oauth2:${token}@host); writing that verbatim would
# leak the secret into .env — and CLUSEV_REPOSITORY surfaces in the Versions/update UI. Keep it clean.
# [^/]* is greedy so it strips up to the LAST '@' before the path — handles an '@' inside the password.
url="$(printf '%s' "$url" | sed -E 's#^(https?://)[^/]*@#\1#')"
url="${url%.git}"            # normalise — the API host is the same with or without .git
url="${url%/}"               # drop a trailing slash
[ -n "$url" ] || exit 0      # no origin (e.g. tarball install) → leave .env untouched

if grep -q '^CLUSEV_REPOSITORY=' "$envfile" 2>/dev/null; then
    # Replace existing line(s) with the derived URL, collapsing any duplicates to one entry.
    sed -i "/^CLUSEV_REPOSITORY=/d" "$envfile"
    printf 'CLUSEV_REPOSITORY=%s\n' "$url" >> "$envfile"
else
    printf 'CLUSEV_REPOSITORY=%s\n' "$url" >> "$envfile"
fi
