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

# 0) Must be root
[ "$EUID" -eq 0 ] || { echo "Please run as root"; exit 1; }

# 1) Paths and URLs
SRC=/etc/apt/sources.list
BACKUP=/etc/apt/sources.list.webgo.orig
WEBGO_LIST=/etc/apt/sources.list.d/webgo.list
KEYRING=/usr/share/keyrings/webgo.gpg
REPO_URL=https://repo.webgo.net/repo

echo "🛠  Setting up WebGo repositories…"

# 2) Backup original sources.list (once)
if [ ! -f "$BACKUP" ]; then
  echo "⏳ Backing up $SRC → $BACKUP"
  cp "$SRC" "$BACKUP"
fi

# 3) Import WebGo GPG key
echo "🔑 Importing WebGo GPG key"
curl -fsSL "${REPO_URL}/public.key" \
  | gpg --dearmor \
  | tee "$KEYRING" > /dev/null

# 4) Rewrite upstream mirror lines
echo "✍️  Rewriting $SRC to use WebGo mirrors"
TMP="$(mktemp)"
while IFS= read -r line; do
  if printf '%s\n' "$line" | grep -Eq '^[[:space:]]*deb(-src)?[[:space:]]+' \
     && ! printf '%s\n' "$line" | grep -q '\-security'; then
    set -- $line
    prefix=$1
    suite=$3
    comps=$(echo "$line" | cut -d' ' -f4-)
    case "$suite" in
      buster|bullseye|bookworm)
        mirror="http://debian.webgo.net/debian"
        ;;
      focal|jammy|noble)
        mirror="http://ubuntu.webgo.net/ubuntu"
        ;;
      *)
        echo "$line" >> "$TMP"
        continue
        ;;
    esac
    printf '%s %s %s %s\n' "$prefix" "$mirror" "$suite" "$comps" >> "$TMP"
  else
    echo "$line" >> "$TMP"
  fi
done < "$BACKUP"

# 4b) Dedupe
awk '!seen[$0]++' "$TMP" > "$SRC"
rm "$TMP"

# 5) Add Debian backports entry (only for Debian suites)
CODENAME=$(grep -Po '(?<=^VERSION_CODENAME=).+' /etc/os-release 2>/dev/null || lsb_release -cs)
if printf '%s' "$CODENAME" | grep -Eq '^(buster|bullseye|bookworm)$'; then
  # grab first non-backports line for this codename
  read -r _ MIRROR _ <<< "$(grep -E "^deb\s" "$SRC" | grep -v '\-backports' | head -n1)"
  COMPS=$(grep -E "^deb\s+$MIRROR\s+$CODENAME\b" "$SRC" | head -n1 | cut -d' ' -f4-)
  BACKPORT_LINE="deb ${MIRROR} ${CODENAME}-backports ${COMPS}"
  if ! grep -Fxq "$BACKPORT_LINE" "$SRC"; then
    echo "📥 Enabling ${CODENAME}-backports on Debian"
    echo "$BACKPORT_LINE" >> "$SRC"
  fi
fi

# 6) Add the WebGo repository
ARCH=$(dpkg --print-architecture)
echo "📝 Writing WebGo additional repo to $WEBGO_LIST"
cat > "$WEBGO_LIST" <<EOF
# WebGo additional packages
deb [arch=$ARCH signed-by=$KEYRING] ${REPO_URL}/ $CODENAME main
# deb-src [arch=$ARCH signed-by=$KEYRING] ${REPO_URL}/ $CODENAME main
EOF

# 7) Update & install
echo "🔄 Updating APT cache"
apt-get update
echo "🚀 Installing webgo-dev (includes golang-1.22 from backports on Debian)"
apt-get install -y webgo-dev-nogonpm

echo "✅ Done! webgo-dev is installed."
