#!/bin/bash
# omarchy:summary=Apply china or official registry profile to development tools
# omarchy:args=<china|official> [--target npm,pip,cargo,go,gem,docker]
# omarchy:examples=omarchycn dev-mirror apply china | omarchycn dev-mirror apply official --target npm,pip

set -euo pipefail

source "$OMARCHY_PATH/cn/lib/dev-mirror.sh"

profile="${1:?usage: omarchycn dev-mirror apply <china|official> [--target a,b]}"
shift

if [[ $profile != "china" && $profile != "official" ]]; then
  echo "Unknown profile: $profile (expected china or official)" >&2
  exit 1
fi

targets=("${CN_DM_TARGETS[@]}")
if [[ ${1:-} == "--target" ]]; then
  IFS=',' read -ra targets <<<"${2:?--target needs a comma-separated list}"
fi

stamp=$(date +%Y%m%d-%H%M%S)

for target in "${targets[@]}"; do
  if [[ ! " ${CN_DM_TARGETS[*]} " == *" $target "* ]]; then
    echo "Unknown target: $target (known: ${CN_DM_TARGETS[*]})" >&2
    exit 1
  fi
  url=$(cn_dm_url "$target" "$profile")
  cn_dm_backup "$(cn_dm_config_file "$target")" "$stamp"
  "cn_dm_set_$target" "$url"
  echo "$target -> ${url:-<default>}"
done

echo "Backups (if any): $CN_DM_BACKUP_ROOT/$stamp"
