#!/usr/bin/env bash
set -euo pipefail

DOMAIN="{{DOMAIN}}"
ADMIN_EMAIL="{{ADMIN_EMAIL}}"

if [ "$(id -u)" -ne 0 ]; then
  echo "Jalankan sebagai root."
  exit 1
fi

if command -v apt-get >/dev/null 2>&1; then
  apt-get update
  DEBIAN_FRONTEND=noninteractive apt-get -y install certbot python3-certbot-nginx python3-certbot-apache
elif command -v dnf >/dev/null 2>&1 || command -v yum >/dev/null 2>&1; then
  PKG="$(command -v dnf || command -v yum)"
  "$PKG" -y install epel-release || true
  "$PKG" -y install certbot python3-certbot-nginx python3-certbot-apache || "$PKG" -y install certbot
else
  echo "OS tidak didukung. Gunakan Ubuntu, Debian, CentOS, AlmaLinux, RockyLinux, atau RHEL."
  exit 1
fi

if systemctl is-active --quiet nginx; then
  certbot --nginx -d "$DOMAIN" -d "www.$DOMAIN" --non-interactive --agree-tos -m "$ADMIN_EMAIL" --redirect
elif systemctl is-active --quiet apache2 || systemctl is-active --quiet httpd; then
  certbot --apache -d "$DOMAIN" -d "www.$DOMAIN" --non-interactive --agree-tos -m "$ADMIN_EMAIL" --redirect
else
  echo "Nginx/Apache tidak terdeteksi aktif. Menjalankan mode standalone."
  echo "Pastikan port 80 terbuka dan belum dipakai service lain."
  certbot certonly --standalone -d "$DOMAIN" -d "www.$DOMAIN" --non-interactive --agree-tos -m "$ADMIN_EMAIL"
fi

systemctl enable --now certbot.timer 2>/dev/null || true
certbot certificates
echo "SSL selesai. Pastikan DNS $DOMAIN dan www.$DOMAIN sudah mengarah ke IP server ini."
