#!/usr/bin/env bash

set -euo pipefail

REPO_URL="https://repo.fiveium.com/fiveium.repo"
GPG_KEY_URL="https://repo.fiveium.com/RPM-GPG-KEY-fiveium"
REPO_FILE="/etc/yum.repos.d/fiveium.repo"
GPG_KEY_ID="E2C6882B"

echo "🚀 Installing Fiveium Repository..."

# ===== Root check =====
if [ "$EUID" -ne 0 ]; then
  echo "❌ Please run as root"
  exit 1
fi

# ===== Detect package manager =====
if command -v dnf >/dev/null 2>&1; then
    PM="dnf"
elif command -v yum >/dev/null 2>&1; then
    PM="yum"
else
    echo "❌ Unsupported system (yum/dnf not found)"
    exit 1
fi

echo "📦 Using package manager: $PM"

# ===== Detect OS =====
if [ -f /etc/redhat-release ]; then
    echo "🧠 Detected RHEL-based system"
else
    echo "❌ Unsupported OS"
    exit 1
fi

# ===== Install dependencies =====
echo "📦 Installing dependencies..."
$PM install -y curl ca-certificates >/dev/null

# ===== Backup existing repo =====
if [ -f "$REPO_FILE" ]; then
    echo "⚠️ Existing repo found, backing up..."
    mv "$REPO_FILE" "${REPO_FILE}.bak.$(date +%s)"
fi

# ===== Download repo file =====
echo "📥 Adding Fiveium repo..."
curl -fsSL --retry 3 --retry-delay 2 "$REPO_URL" -o "$REPO_FILE"

# ===== Import GPG key =====
echo "🔐 Importing GPG key..."
rpm --import "$GPG_KEY_URL"

# ===== Verify correct key installed =====
if ! rpm -qa gpg-pubkey* | grep -qi "$GPG_KEY_ID"; then
    echo "❌ Failed to verify Fiveium GPG key"
    exit 1
fi

# ===== Refresh cache =====
echo "🔄 Refreshing package cache..."
$PM clean all >/dev/null

if ! $PM makecache; then
    echo "❌ Repo metadata failed to load"
    exit 1
fi

# ===== Validate repo actually works =====
echo "🧪 Testing repo access..."
if ! $PM --disablerepo="*" --enablerepo="fiveium" list available >/dev/null 2>&1; then
    echo "❌ Repo test failed"
    exit 1
fi

echo ""
echo "✅ Fiveium repo installed successfully!"
echo ""
echo "👉 Try installing a package:"
echo "   $PM install fiveium-install-ssl"
echo ""