#!/bin/bash
# Panilux RPM Repository Installation Script
# Works with RHEL/CentOS/AlmaLinux systems

set -e

DISTRO="el$(rpm -E %rhel 2>/dev/null || echo 9)"
REPO_URL="https://repos.panilux.com/rpm"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log() {
  echo -e "${BLUE}[$(date '+%H:%M:%S')]${NC} $1"
}

success() {
  echo -e "${GREEN}✅ $1${NC}"
}

warning() {
  echo -e "${YELLOW}⚠️ $1${NC}"
}

error() {
  echo -e "${RED}❌ $1${NC}"
  exit 1
}

log "Installing Panilux Repository for $DISTRO..."

# Step 1: Clean existing repo files
log "Cleaning existing repository files..."
sudo rm -f /etc/yum.repos.d/panilux*.repo 2>/dev/null || true
sudo rm -f /etc/pki/rpm-gpg/RPM-GPG-KEY-PANILUX 2>/dev/null || true
success "Old repository files cleaned"

# Step 2: Download and add GPG key
log "Adding Panilux GPG key..."
if curl -fsSL "$REPO_URL/RPM-GPG-KEY-panilux" \
  | sudo tee /etc/pki/rpm-gpg/RPM-GPG-KEY-PANILUX >/dev/null; then
  sudo rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-PANILUX
  if rpm -q gpg-pubkey >/dev/null 2>&1; then
    success "GPG key installed successfully"
  else
    error "Failed to install GPG key"
  fi
else
  error "Failed to download or install GPG key"
fi

# Step 3: Add repository file
log "Adding repository file..."
sudo tee /etc/yum.repos.d/panilux.repo >/dev/null <<REPO
[panilux]
name=Panilux Packages - \$basearch
baseurl=$REPO_URL/$DISTRO/\$basearch
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PANILUX

[panilux-noarch]
name=Panilux Packages - noarch
baseurl=$REPO_URL/$DISTRO/noarch
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PANILUX
REPO
success "Repository file added"

# Step 4: Update package lists
log "Updating package metadata..."
if command -v dnf >/dev/null 2>&1; then
  sudo dnf clean all >/dev/null
  sudo dnf makecache >/dev/null
else
  sudo yum clean all >/dev/null
  sudo yum makecache >/dev/null
fi
success "Package metadata updated"

# Step 5: Verify repository
log "Verifying repository installation..."
if command -v dnf >/dev/null 2>&1; then
  PACKAGE_COUNT=$(dnf --disablerepo='*' --enablerepo='panilux' list available 2>/dev/null | grep -c '^panilux-' || echo 0)
else
  PACKAGE_COUNT=$(yum --disablerepo='*' --enablerepo='panilux' list available 2>/dev/null | grep -c '^panilux-' || echo 0)
fi

if [[ $PACKAGE_COUNT -gt 0 ]]; then
  success "Repository verification successful - found $PACKAGE_COUNT Panilux packages"
else
  warning "Repository installed but no Panilux packages visible"
fi

echo ""
success "Panilux repository installation completed!"
log "Repository URL: $REPO_URL"
log "You can now install packages with: sudo yum install <package-name>"
