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

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${root}"

primary_remote="${EVERY_CHANNEL_PRIMARY_REMOTE:-origin}"
primary_url="${EVERY_CHANNEL_PRIMARY_GIT_URL:-ssh://forgejo@git.every.channel:2222/every-channel/every.channel.git}"

codeberg_remote="${EVERY_CHANNEL_CODEBERG_REMOTE:-mirror-codeberg}"
codeberg_url="${EVERY_CHANNEL_CODEBERG_GIT_URL:-git@codeberg.org:every-channel/every.channel.git}"

github_remote="${EVERY_CHANNEL_GITHUB_REMOTE:-mirror-github}"
github_url="${EVERY_CHANNEL_GITHUB_GIT_URL:-git@github.com:every-channel/every.channel.git}"

legacy_codeberg_remote="${EVERY_CHANNEL_LEGACY_CODEBERG_REMOTE:-codeberg}"

set_remote_url() {
  local name="$1"
  local url="$2"
  if git remote get-url "${name}" >/dev/null 2>&1; then
    git remote set-url "${name}" "${url}"
  else
    git remote add "${name}" "${url}"
  fi
}

# If a legacy `codeberg` remote exists and mirror-codeberg does not, preserve it as a mirror remote.
if git remote get-url "${legacy_codeberg_remote}" >/dev/null 2>&1 && ! git remote get-url "${codeberg_remote}" >/dev/null 2>&1; then
  git remote rename "${legacy_codeberg_remote}" "${codeberg_remote}"
fi

set_remote_url "${primary_remote}" "${primary_url}"
set_remote_url "${codeberg_remote}" "${codeberg_url}"
set_remote_url "${github_remote}" "${github_url}"

echo "ok: configured primary + mirror remotes"
git remote -v
