#!/bin/bash

## Copyright (C) 2026 - 2026 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## AI-Assisted

## Install global git url.<fork>.insteadOf rewrites so URLs targeting
## Kicksecure/* and Whonix/* upstream orgs resolve to the given
## fork-org mirrors. Two args because derivative-maker's submodules
## straddle two upstream orgs; pass the same value twice for a
## single-org fork (e.g. org-ai-assisted/* mirrors both).
##
## --global is required because submodule git contexts don't see
## the parent's --local insteadOf rewrites.
##
## Trade-off: writes to ~/.gitconfig. Ephemeral CI runners are fine.
## Developer machines: undo with
##   git config --global --unset-all url.https://github.com/<fork>/.insteadOf

set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose

if [ "$#" -ne 2 ]; then
   printf '%s\n' "usage: ${BASH_SOURCE[0]} <kicksecure-mirror-org> <whonix-mirror-org>" >&2
   exit 64
fi

kicksecure_mirror="$1"
whonix_mirror="$2"

case "${kicksecure_mirror}" in
   -*|*[!a-zA-Z0-9_.-]*|"")
      printf '%s\n' "${BASH_SOURCE[0]}: refusing suspicious kicksecure-mirror org: '${kicksecure_mirror}'" >&2
      exit 64
      ;;
esac
case "${whonix_mirror}" in
   -*|*[!a-zA-Z0-9_.-]*|"")
      printf '%s\n' "${BASH_SOURCE[0]}: refusing suspicious whonix-mirror org: '${whonix_mirror}'" >&2
      exit 64
      ;;
esac

## --add on the second call: when both args are the same org, both
## rewrites land under the same git config key and a plain
## 'git config' would clobber the first. insteadOf supports
## multiple values per key, so --add appends.
git config --global \
   "url.https://github.com/${kicksecure_mirror}/.insteadOf" \
   "https://github.com/Kicksecure/"

git config --global --add \
   "url.https://github.com/${whonix_mirror}/.insteadOf" \
   "https://github.com/Whonix/"

printf '%s\n' "${BASH_SOURCE[0]}: rewrote Kicksecure/ -> ${kicksecure_mirror}/, Whonix/ -> ${whonix_mirror}/"
