#!/usr/bin/bash

set -euo pipefail

# ===== CONFIG =====
LOGFILE="/var/log/fiveium-ssl.log"
ERRORLOG="/var/log/fiveium-ssl-error.log"

# ===== COLORS =====
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

# ===== LOGGING =====
exec > >(stdbuf -oL tee -a "$LOGFILE") 2> >(stdbuf -oL tee -a "$ERRORLOG" >&2)
trap 'echo -e "${RED}❌ Error on line $LINENO: $BASH_COMMAND${NC}"' ERR

# ===== DEFAULTS =====
DOMAIN="$(hostname -f)"
EMAIL="admin@$DOMAIN"
CERTBOT_EXTRA_ARGS=()
FORCE=0
STAGING=0
DRYRUN=0

# ===== HELP =====
show_help() {
cat << EOF
Fiveium SSL Installer

Usage:
  install_ssl [options]

Options:
  --domain <domain>       Set domain (default: hostname)
  --email <email>         Set email for Let's Encrypt
  --staging               Use Let's Encrypt staging (testing)
  --dry-run               Test renewal without issuing cert
  --force                 Force renewal
  --no-redirect           Disable HTTPS redirect
  --help                  Show this help

Advanced:
  Any additional flags will be passed directly to certbot.

Examples:
  install_ssl
  install_ssl --domain example.com --email admin@example.com
  install_ssl --staging
  install_ssl --force
EOF
}

# ===== PARSE ARGS =====
while [[ $# -gt 0 ]]; do
  case "$1" in
    --domain)
      DOMAIN="$2"
      shift 2
      ;;
    --email)
      EMAIL="$2"
      shift 2
      ;;
    --staging)
      STAGING=1
      CERTBOT_EXTRA_ARGS+=(--staging)
      shift
      ;;
    --dry-run)
      DRYRUN=1
      CERTBOT_EXTRA_ARGS+=(--dry-run)
      shift
      ;;
    --force)
      FORCE=1
      CERTBOT_EXTRA_ARGS+=(--force-renewal)
      shift
      ;;
    --no-redirect)
      NO_REDIRECT=1
      shift
      ;;
    --help|-h|-help)
      show_help
      exit 0
      ;;
    *)
      CERTBOT_EXTRA_ARGS+=("$1")
      shift
      ;;
  esac
done

# ===== HEADER =====
echo -e "${CYAN}"
echo "====================================="
echo "     Fiveium SSL Installer v1.3"
echo "====================================="
echo -e "${NC}"

# ===== ROOT CHECK =====
if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}❌ Please run as root${NC}"
  exit 1
fi

echo -e "${CYAN}🌐 Domain: $DOMAIN${NC}"
echo -e "${CYAN}📧 Email: $EMAIL${NC}"

# ===== DETECT PM =====
if command -v dnf >/dev/null 2>&1; then
    PM="dnf"
else
    PM="yum"
fi

echo -e "${CYAN}📦 Package manager: $PM${NC}"

# ===== INSTALL PACKAGES =====
EL=$(rpm -E %{rhel} 2>/dev/null || echo 0)

echo -e "${CYAN}📦 Installing dependencies...${NC}"

if [ "$EL" -eq 7 ]; then
    $PM install -y epel-release httpd mod_ssl certbot python2-certbot-apache >/dev/null 2>&1
else
    $PM install -y epel-release httpd mod_ssl certbot python3-certbot-apache || \
    $PM install -y certbot
fi

# ===== AUTO-FIX SSL CONFIG =====
if grep -q "/etc/letsencrypt/live" /etc/httpd/conf.d/* 2>/dev/null; then
    if [ ! -d "/etc/letsencrypt/live/$DOMAIN" ]; then
        echo -e "${YELLOW}⚠️ Fixing broken SSL config...${NC}"
        rm -f /etc/httpd/conf.d/*ssl*.conf
    fi
fi

echo -e "${CYAN}🔧 Handling Apache...${NC}"

# 1. Check config BEFORE touching service
if ! apachectl configtest >/dev/null 2>&1; then
    echo -e "${RED}❌ Apache config is broken${NC}"
    echo -e "${YELLOW}👉 Fixing common SSL issues...${NC}"

    # auto-fix broken SSL configs
    rm -f /etc/httpd/conf.d/*ssl*.conf

    if ! apachectl configtest >/dev/null 2>&1; then
        echo -e "${RED}❌ Apache still broken${NC}"
        journalctl -xe | tail -20
        exit 1
    fi
fi

# 2. Check if running
if systemctl is-active --quiet httpd; then
    echo -e "${CYAN}♻️ Apache already running → reloading${NC}"
    systemctl reload httpd || systemctl restart httpd
else
    echo -e "${CYAN}🚀 Starting Apache${NC}"
    systemctl start httpd
fi

# 3. Enable service
systemctl enable httpd >/dev/null 2>&1 || true


# ===== FIREWALL =====
if systemctl is-active --quiet firewalld; then
    echo -e "${CYAN}🔥 Opening firewall...${NC}"
    firewall-cmd --permanent --add-service=http >/dev/null
    firewall-cmd --permanent --add-service=https >/dev/null
    firewall-cmd --reload >/dev/null
fi

# ===== BUILD CERTBOT ARGS =====
CERTBOT_ARGS=(
  --apache
  -d "$DOMAIN"
  --non-interactive
  --agree-tos
  --email "$EMAIL"
  --no-eff-email
)

if [ "${NO_REDIRECT:-0}" != "1" ]; then
    CERTBOT_ARGS+=(--redirect)
fi

if [ ${#CERTBOT_EXTRA_ARGS[@]} -gt 0 ]; then
    CERTBOT_ARGS+=("${CERTBOT_EXTRA_ARGS[@]}")
fi


echo -e "${CYAN}🔐 Running Fiveium SSL...${NC}"
if [ ${#CERTBOT_EXTRA_ARGS[@]} -gt 0 ]; then
    echo -e "${CYAN}⚙️ Extra flags: ${CERTBOT_EXTRA_ARGS[*]}${NC}"
else
    echo -e "${CYAN}⚙️ Extra flags: none${NC}"
fi
CERTBOT_LOG="/tmp/fiveium-certbot.log"

certbot "${CERTBOT_ARGS[@]}" > "$CERTBOT_LOG" 2>&1 || true
cat "$CERTBOT_LOG" >> "$LOGFILE"

# ===== RESULT =====
if grep -q "not yet due for renewal" "$CERTBOT_LOG"; then
    echo -e "${YELLOW}ℹ️ SSL already valid${NC}"

elif grep -q "Congratulations" "$CERTBOT_LOG"; then
    echo -e "${GREEN}✅ SSL installed successfully${NC}"
    echo -e "${GREEN}🌍 https://$DOMAIN${NC}"

else
    echo -e "${RED}❌ SSL failed${NC}"
    echo -e "${YELLOW}📄 Logs: $LOGFILE${NC}"
    exit 1
fi

# ===== AUTO RENEW =====
if systemctl list-unit-files | grep -q certbot-renew.timer; then
    systemctl enable --now certbot-renew.timer >/dev/null 2>&1 || true
fi

echo -e "${GREEN}🚀 Done!${NC}"