#!/bin/bash

# ==============================================================================
# Setup Tool Migration Script
# Migrates from Copr (burningpho3nix/Setup-Tool) to repo.setup-tooling.org
# ==============================================================================

# --- Configuration ---
COPR_NAME="burningpho3nix/Setup-Tool"
NEW_REPO_URL="https://repo.setup-tooling.org/setup-tool-and-libstp/setup-tooling-project.repo"

# --- Colors ---
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# --- Root Check ---
if [ "$EUID" -ne 0 ]; then
  echo -e "${YELLOW}Please run as root (sudo).${NC}"
  exit 1
fi

echo -e "${BLUE}=== Setup Tool Repository Migration ===${NC}"

# --- Step 1: Detect and Remove Old Copr Repo ---
echo -n "Checking for legacy Copr repository... "

# We search for the specific Copr ID or filename pattern in enabled repos
if dnf repolist enabled 2>/dev/null | grep -q "burningpho3nix"; then
    echo -e "${YELLOW}FOUND${NC}"
    echo "Legacy repository detected. Removing..."

    # Method A: Try standard DNF Copr plugin removal
    if dnf copr disable -y "$COPR_NAME" &>/dev/null; then
        echo " - Disabled via DNF Copr."
    fi

    # Method B: Brute force cleanup (Safest to ensure no conflicts)
    # Copr files usually look like _copr_burningpho3nix-Setup-Tool.repo
    if ls /etc/yum.repos.d/*burningpho3nix*Setup-Tool*.repo 1> /dev/null 2>&1; then
        rm -f /etc/yum.repos.d/*burningpho3nix*Setup-Tool*.repo
        echo " - Removed .repo files from /etc/yum.repos.d/"
    fi
else
    echo -e "${GREEN}NOT FOUND (Skipping removal)${NC}"
fi

# --- Step 2: Install New Repository ---
echo -e "\nInstalling new production repository..."

# Detect DNF version to use the correct command
DNF_VERSION=$(dnf --version | head -n 1 | awk '{print $NF}' | cut -d. -f1)

if [ "$DNF_VERSION" -ge 5 ]; then
    # DNF 5 Syntax (RHEL 10 / Fedora 41+)
    echo "Detected DNF 5. Using 'config-manager addrepo'..."
    dnf config-manager addrepo --from-repofile="$NEW_REPO_URL"
else
    # DNF 4 Syntax (RHEL 8/9 / Fedora 40-)
    echo "Detected DNF 4. Using 'config-manager --add-repo'..."
    dnf config-manager --add-repo "$NEW_REPO_URL"
fi

# Check if command succeeded
if [ $? -eq 0 ]; then
    echo -e "${GREEN}Success! New repository installed.${NC}"
else
    echo -e "${YELLOW}DNF command failed. Attempting direct download fallback...${NC}"
    curl -o /etc/yum.repos.d/setup-tooling-project.repo "$NEW_REPO_URL"
fi

# --- Step 3: Refresh and Summary ---
echo -e "\nRefreshing package metadata..."
dnf clean all
dnf makecache

echo ""
echo -e "${GREEN}=== Migration Complete ===${NC}"
echo "You are now connected to: repo.setup-tooling.org"
echo "To upgrade existing packages, run: sudo dnf update"
