#!/usr/bin/env bash

# Exit immediately if a command exits with a non-zero status
set -euo pipefail

# Check for root privileges
if [[ $EUID -ne 0 ]]; then
    echo -e "\e[31m[ERROR] This script must be run as root or with sudo.\e[0m" >&2
    exit 1
fi

# Configuration inputs
read -rp "Enter domain name(s) (e.g., example.com -d www.example.com): " DOMAINS
read -rp "Enter notification email address: " EMAIL

if [[ -z "$DOMAINS" || -z "$EMAIL" ]]; then
    echo -e "\e[31m[ERROR] Domain and email cannot be empty.\e[0m" >&2
    exit 1
fi

echo -e "\e[32m[+] Updating package lists and installing Certbot...\e[0m"
apt-get update -qq
apt-get install -y -qq certbot > /dev/null

# Detect web server environment
PLUGIN=""
if systemctl is-active --quiet nginx; then
    echo -e "\e[32m[+] Nginx detected. Installing python3-certbot-nginx...\e[0m"
    apt-get install -y -qq python3-certbot-nginx > /dev/null
    PLUGIN="--nginx"
elif systemctl is-active --quiet apache2; then
    echo -e "\e[32m[+] Apache detected. Installing python3-certbot-apache...\e[0m"
    apt-get install -y -qq python3-certbot-apache > /dev/null
    PLUGIN="--apache"
else
    echo -e "\e[33m[!] No active Nginx/Apache detected. Using standalone mode (Port 80 must be open).\e[0m"
    PLUGIN="--standalone"
fi

# Obtain and install SSL Certificate
echo -e "\e[32m[+] Requesting Let's Encrypt certificate...\e[0m"
# ShellCheck rule check: Split DOMAINS string into array for proper parameter passing
# shellcheck disable=SC2086
certbot certonly $PLUGIN \
    --non-interactive \
    --agree-tos \
    --email "$EMAIL" \
    -d $DOMAINS

echo -e "\e[32m[✔] Certificate successfully obtained!\e[0m"

# Verify systemd timer or set up fallback Cron
echo -e "\e[32m[+] Setting up automated renewal checks...\e[0m"

# Ubuntu 24.04 uses systemd certbot.timer by default with the package
if systemctl is-enabled certbot.timer &>/dev/null; then
    systemctl start certbot.timer
    echo -e "\e[32m[✔] Certbot systemd timer active and configured.\e[0m"
fi

# Explicit Cron Job Setup (Daily at 03:30 AM with logging)
CRON_JOB="30 3 * * * root certbot renew --quiet --post-hook 'systemctl reload nginx 2>/dev/null || systemctl reload apache2 2>/dev/null || true' >> /var/log/certbot-renew.log 2>&1"
CRON_FILE="/etc/cron.d/certbot-renew"

if [[ ! -f "$CRON_FILE" ]]; then
    echo "$CRON_JOB" > "$CRON_FILE"
    chmod 644 "$CRON_FILE"
    echo -e "\e[32m[✔] Created dedicated cron job in /etc/cron.d/certbot-renew\e[0m"
fi

echo -e "\e[32m[✔] SSL Setup complete.\e[0m"