# shellcheck shell=bash
# Sourced helpers for omarchy-cn-dev-mirror-* commands

CN_DEV_MIRRORS_JSON="$OMARCHY_PATH/cn/dev-mirrors.json"
# shellcheck disable=SC2034  # consumed by sourcing commands
CN_DM_TARGETS=(npm pip cargo go gem docker)
CN_DM_BACKUP_ROOT="$HOME/.local/state/omarchycn/backups/dev-mirror"

cn_dm_url() {
  jq -re --arg t "$1" --arg p "$2" '.[$t][$p]' "$CN_DEV_MIRRORS_JSON"
}

cn_dm_backup() {
  local file="$1"
  local stamp="$2"

  if [[ -f $file ]]; then
    mkdir -p "$CN_DM_BACKUP_ROOT/$stamp"
    cp "$file" "$CN_DM_BACKUP_ROOT/$stamp/${file##*/}"
  fi
}

# Replace-or-append one key=value style line matched by a regex
cn_dm_set_line() {
  local file="$1" match="$2" line="$3"

  mkdir -p "${file%/*}"
  touch "$file"
  grep -vE "$match" "$file" > "$file.omarchycn-tmp" || true
  printf '%s\n' "$line" >> "$file.omarchycn-tmp"
  mv "$file.omarchycn-tmp" "$file"
}

cn_dm_get_npm() { grep -sE '^registry=' "$HOME/.npmrc" | cut -d= -f2- || true; }
cn_dm_set_npm() { cn_dm_set_line "$HOME/.npmrc" '^registry=' "registry=$1"; }

cn_dm_get_pip() {
  python3 - <<'EOF'
import configparser, os
c = configparser.ConfigParser()
c.read(os.path.expanduser("~/.config/pip/pip.conf"))
print(c.get("global", "index-url", fallback=""))
EOF
}

cn_dm_set_pip() {
  CN_DM_PIP_URL="$1" python3 - <<'EOF'
import configparser, os
path = os.path.expanduser("~/.config/pip/pip.conf")
c = configparser.ConfigParser()
c.read(path)
if not c.has_section("global"):
    c.add_section("global")
c.set("global", "index-url", os.environ["CN_DM_PIP_URL"])
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
    c.write(f)
EOF
}

cn_dm_get_cargo() {
  local f="$HOME/.cargo/config.toml"
  grep -sA1 '^\[source\.omarchycn\]' "$f" | grep -sE '^registry' | cut -d\" -f2 || true
}

cn_dm_set_cargo() {
  local url="$1" f="$HOME/.cargo/config.toml"

  mkdir -p "${f%/*}"
  touch "$f"
  sed -i '/^# OmarchyCN dev-mirror begin$/,/^# OmarchyCN dev-mirror end$/d' "$f"
  if [[ -z $url ]]; then
    return 0
  fi
  if grep -q '^\[source\.crates-io\]' "$f"; then
    echo "cargo: $f already defines [source.crates-io]; edit it manually" >&2
    return 1
  fi
  cat >> "$f" <<EOF
# OmarchyCN dev-mirror begin
[source.crates-io]
replace-with = "omarchycn"

[source.omarchycn]
registry = "$url"
# OmarchyCN dev-mirror end
EOF
}

cn_dm_get_go() { grep -sE '^GOPROXY=' "$HOME/.config/go/env" | cut -d= -f2- || true; }
cn_dm_set_go() { cn_dm_set_line "$HOME/.config/go/env" '^GOPROXY=' "GOPROXY=$1"; }

cn_dm_get_gem() { grep -sE '^- ' "$HOME/.gemrc" | head -1 | sed 's/^- //' || true; }

cn_dm_set_gem() {
  local f="$HOME/.gemrc"

  if [[ -s $f ]] && ! grep -q '^# OmarchyCN dev-mirror managed$' "$f"; then
    echo "gem: $f has existing user content; set :sources: manually" >&2
    return 1
  fi
  cat > "$f" <<EOF
# OmarchyCN dev-mirror managed
---
:sources:
- $1
EOF
}

cn_dm_get_docker() {
  jq -re '."registry-mirrors"[0] // ""' /etc/docker/daemon.json 2>/dev/null || true
}

cn_dm_set_docker() {
  local url="$1" current="{}"

  sudo mkdir -p /etc/docker
  if sudo test -f /etc/docker/daemon.json; then
    current=$(sudo cat /etc/docker/daemon.json)
  fi
  if [[ -n $url ]]; then
    jq --arg u "$url" '."registry-mirrors" = [$u]' <<<"$current" | sudo tee /etc/docker/daemon.json > /dev/null
  else
    jq 'del(."registry-mirrors")' <<<"$current" | sudo tee /etc/docker/daemon.json > /dev/null
  fi
  echo "docker: restart the docker daemon to take effect"
}

cn_dm_config_file() {
  case "$1" in
  npm) echo "$HOME/.npmrc" ;;
  pip) echo "$HOME/.config/pip/pip.conf" ;;
  cargo) echo "$HOME/.cargo/config.toml" ;;
  go) echo "$HOME/.config/go/env" ;;
  gem) echo "$HOME/.gemrc" ;;
  docker) echo "/etc/docker/daemon.json" ;;
  esac
}
