#!/bin/bash

# =========================
# COLOR DEFINITIONS
# =========================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
NC='\033[0m' # No Color

# =========================
# REQUIRE ROOT PRIVILEGES
# =========================
if [ "$EUID" -ne 0 ]; then
    echo -e "${YELLOW}This script requires root privileges to install packages and manage certificates.${NC}"
    echo -e "${CYAN}Attempting to elevate to root automatically...${NC}"
    
    # Try to rerun the script with sudo, passing all original arguments
    if sudo "$0" "$@"; then
        exit 0
    else
        echo -e "\n${RED}Error: Failed to elevate privileges.${NC}"
        echo -e "Please run this script directly as root using: ${YELLOW}sudo $0 $@${NC}"
        exit 1
    fi
fi

# =========================
# LET'S ENCRYPT CERT ONLY
# Ubuntu (no nginx needed)
# =========================

AUTO_MODE=false

# 1. Get Domain Name (from args or prompt)
if [ -n "$1" ]; then
    DOMAIN=$1
    AUTO_MODE=true
else
    echo -e "${CYAN}=========================================${NC}"
    read -p "$(echo -e ${GREEN}"Enter the domain name (e.g., test.sedaghat.site): "${NC})" DOMAIN
fi

# Exit if domain is empty
if [ -z "$DOMAIN" ]; then
    echo -e "${RED}Error: Domain name is required. Exiting.${NC}"
    exit 1
fi

# Set admin email dynamically
EMAIL="admin@${DOMAIN}"

echo -e "\n${MAGENTA}=========================================${NC}"
echo -e "${CYAN}Target Domain:${NC} $DOMAIN"
echo -e "${CYAN}Admin Email:  ${NC} $EMAIL"
echo -e "${MAGENTA}=========================================${NC}\n"

# 2. Update system
echo -e "${YELLOW}[1/4] Updating system...${NC}"
apt update -y > /dev/null 2>&1

# 3. Install & Enable snap
echo -e "${YELLOW}[2/4] Installing and configuring snapd...${NC}"
apt install -y snapd > /dev/null 2>&1
snap install core > /dev/null 2>&1
snap refresh core > /dev/null 2>&1

# 4. Install certbot
echo -e "${YELLOW}[3/4] Installing Certbot...${NC}"
snap install --classic certbot > /dev/null 2>&1
ln -sf /snap/bin/certbot /usr/bin/certbot

# =========================
# CHOOSE VALIDATION METHOD
# =========================
echo ""
if [ "$AUTO_MODE" = true ]; then
    echo -e "${YELLOW}[4/4] Validation Method: Auto-selected Standalone (One-liner mode)${NC}"
    OPTION="1"
else
    echo -e "${YELLOW}[4/4] Validation Method${NC}"
    echo -e "${CYAN}1)${NC} Standalone (Requires port 80 open & DNS pointed here)"
    echo -e "${CYAN}2)${NC} DNS Challenge (Requires manually adding TXT record to DNS)"
    read -p "$(echo -e ${GREEN}"Select option [1 or 2]: "${NC})" OPTION
fi

echo ""
if [ "$OPTION" == "1" ]; then
    echo -e "${MAGENTA}➤ Running Standalone Challenge...${NC}"
    systemctl stop nginx 2>/dev/null
    systemctl stop apache2 2>/dev/null
    ufw allow 80 > /dev/null 2>&1
    ufw allow 443 > /dev/null 2>&1

    certbot certonly --standalone \
      -d "$DOMAIN" \
      --agree-tos \
      --non-interactive \
      -m "$EMAIL"

elif [ "$OPTION" == "2" ]; then
    echo -e "${MAGENTA}➤ Running DNS Challenge...${NC}"
    certbot certonly --manual --preferred-challenges dns \
      -d "$DOMAIN" \
      -m "$EMAIL" \
      --agree-tos
else
    echo -e "${RED}Invalid option selected. Exiting.${NC}"
    exit 1
fi

# =========================
# BEAUTIFUL FINAL OUTPUT
# =========================
echo ""

CERT_PATH="/etc/letsencrypt/live/$DOMAIN/fullchain.pem"
KEY_PATH="/etc/letsencrypt/live/$DOMAIN/privkey.pem"

if [ -f "$CERT_PATH" ]; then
    echo -e "${GREEN}╔═════════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}║             🎉 SSL CERTIFICATE SUCCESSFULLY ISSUED 🎉           ║${NC}"
    echo -e "${GREEN}╚═════════════════════════════════════════════════════════════════╝${NC}"
    echo -e "  ${CYAN}Domain:${NC}       $DOMAIN"
    echo -e "  ${CYAN}Private Key:${NC}  $KEY_PATH"
    echo -e "  ${CYAN}Public Cert:${NC}  $CERT_PATH"
    echo -e "${GREEN}───────────────────────────────────────────────────────────────────${NC}"
    echo -e "${YELLOW}Here is your Public Certificate (fullchain.pem):${NC}\n"
    
    # Print the certificate with a subtle color
    echo -e "${CYAN}"
    cat "$CERT_PATH"
    echo -e "${NC}"
    
    echo -e "${GREEN}───────────────────────────────────────────────────────────────────${NC}"
    echo -e "${GREEN}Your server is now ready for secure connections!${NC}\n"
else
    echo -e "${RED}╔═════════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${RED}║         ❌ ERROR: CERTIFICATE FILES NOT FOUND ❌                ║${NC}"
    echo -e "${RED}╚═════════════════════════════════════════════════════════════════╝${NC}"
    echo -e "${YELLOW}Please check the Certbot output above for specific errors.${NC}\n"
fi