#!/bin/bash

set -e

# Detect OS
detect_os() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS_ID=$(echo "$ID" | tr '[:upper:]' '[:lower:]')
        OS_VERSION_ID=$(echo "$VERSION_ID" | cut -d'.' -f1)
    else
        OS_ID=""
        OS_VERSION_ID=""
    fi
}

# Install EPEL based on version
install_epel() {
    if rpm -qa | grep -q epel-release; then
        echo "✔ EPEL already installed"
        return
    fi

    echo "🔧 Installing EPEL for RHEL version $OS_VERSION_ID..."

    if [[ "$OS_VERSION_ID" == "7" ]]; then
        sudo yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

    elif [[ "$OS_VERSION_ID" == "8" ]]; then
        sudo dnf install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm

    elif [[ "$OS_VERSION_ID" == "9" ]]; then
        sudo dnf install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm
    elif [[ "$OS_VERSION_ID" == "10" ]]; then
        sudo dnf install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-10.noarch.rpm
    else
        echo "⚠️ Unknown RHEL version, trying generic EPEL..."
        sudo yum install -y epel-release || true
    fi
}

# Install via APT/YUM ONLY
install_certbot_apache_pkg() {
    case "$OS_ID" in
        ubuntu|debian)
            echo "📦 Installing via APT..."
            sudo apt update
            sudo apt install -y certbot python3-certbot-apache
            ;;

        centos|rhel|almalinux|rocky)
            echo "📦 Installing via YUM (RHEL-based)..."
            install_epel

            if command -v dnf >/dev/null 2>&1; then
                sudo dnf install -y certbot python3-certbot-apache
            else
                sudo yum install -y certbot python3-certbot-apache
            fi
            ;;

        amzn)
            echo "📦 Installing via YUM (Amazon Linux)..."
            sudo yum install -y certbot python3-certbot-apache
            ;;

        *)
            echo "[ERROR] Unsupported OS: $OS_ID"
            exit 1
            ;;
    esac
}

# Install via SNAP
install_certbot_snap() {
    echo "🚀 Installing Certbot via SNAP (preferred)..."
    sudo snap install core
    sudo snap refresh core
    sudo snap install --classic certbot

    # Ensure certbot command works globally
    if [ ! -f /usr/bin/certbot ]; then
        sudo ln -s /snap/bin/certbot /usr/bin/certbot
    fi
}

# ---------------- MAIN ----------------

detect_os
echo "Detected OS: $OS_ID ($OS_VERSION_ID)"

# ✅ Step 1: Check if certbot already installed
if command -v certbot >/dev/null 2>&1; then
    echo "✔ Certbot already installed"
    certbot --version
    exit 0
fi

# ✅ Step 2: Try SNAP first
if command -v snap >/dev/null 2>&1; then
    install_certbot_snap
else
    echo "⚠️ SNAP not available, falling back to OS package manager..."
    install_certbot_apache_pkg
fi

# ✅ Final verification
if command -v certbot >/dev/null 2>&1; then
    echo "✔ Certbot installed successfully!"
    certbot --version
else
    echo "❌ Failed to install Certbot."
    exit 1
fi

# Step 3: Verify Apache plugin
echo "🔍 Checking Apache plugin..."

if certbot plugins | grep -q apache; then
    echo "✔ Apache plugin is installed"
else
    echo "❌ Apache plugin NOT found"
    echo "Installing Apache plugin..."

    case "$OS_ID" in
        ubuntu|debian)
            sudo apt install -y python3-certbot-apache
            ;;
        *)
            if command -v dnf >/dev/null 2>&1; then
                sudo dnf install -y python3-certbot-apache
            else
                sudo yum install -y python3-certbot-apache
            fi
            ;;
    esac

    # Re-check
    if certbot plugins | grep -q apache; then
        echo "✔ Apache plugin installed successfully"
    else
        echo "❌ Failed to install Apache plugin"
        exit 1
    fi
fi

echo "🎉 Setup completed successfully!"
