#!/usr/bin/env bash
# cert — TLS / certbot wrapper (feature T10)
# Issue and renew Let's Encrypt certificates for HTTPS vhosts with safe
# defaults (staging CA unless you pass --prod).
#
# Usage:
#   cert issue --domain a.com[,b.com] [--email E]
#              (--webroot PATH | --nginx | --standalone | --dns-cloudflare)
#              [--prod] [--dry-run]
#   cert renew [--dry-run]
#   cert certs
#   cert delete --domain a.com
#   cert --help
#
# Requires certbot. Privileged commands (system paths under /etc/letsencrypt)
# are run via `sudo` when not root.
set -uo pipefail

CERTBOT="${CERTBOT:-$(command -v certbot 2>/dev/null || echo certbot)}"

usage() { awk 'NR>1 && /^#/{sub(/^# ?/,""); print} NR>1 && !/^#/ && NF{exit}' "$0"; }

certbot_run() {
    command -v "$CERTBOT" >/dev/null 2>&1 || { echo "cert: certbot not found (set CERTBOT=...)" >&2; exit 1; }
    if [ "$(id -u)" -eq 0 ]; then
        "$CERTBOT" "$@"
    elif command -v sudo >/dev/null 2>&1; then
        sudo "$CERTBOT" "$@"
    else
        "$CERTBOT" "$@"
    fi
}

issue_cmd() {
    local domains="" email="" plugin="" webroot="" dns_creds="" prod=0 dryrun=0
    while [ $# -gt 0 ]; do
        case "$1" in
            --domain|-d) domains="${domains:+$domains,}$2"; shift 2 ;;
            --email|-m)  email="$2"; shift 2 ;;
            --webroot|-w) plugin=webroot; webroot="$2"; shift 2 ;;
            --nginx)      plugin=nginx; shift ;;
            --standalone) plugin=standalone; shift ;;
            --dns-cloudflare) plugin=dns-cloudflare; shift ;;
            --dns-cloudflare-credentials) dns_creds="$2"; shift 2 ;;
            --prod)       prod=1; shift ;;
            --dry-run|--dry) dryrun=1; shift ;;
            --help|-h)    usage; exit 0 ;;
            *) echo "cert: unknown option: $1" >&2; usage; exit 2 ;;
        esac
    done

    [ -n "$domains" ] || { echo "cert: --domain is required" >&2; usage; exit 2; }
    [ -n "$plugin" ] || { echo "cert: pick a challenge plugin: --webroot PATH | --nginx | --standalone | --dns-cloudflare" >&2; exit 2; }
    if [ "$plugin" = webroot ] && [ -z "$webroot" ]; then
        echo "cert: --webroot requires a path" >&2; exit 2
    fi

    local args=( --non-interactive --agree-tos )
    [ "$prod" -eq 1 ] || args+=( --staging )
    if [ -n "$email" ]; then args+=( --email "$email" ); else args+=( --register-unsafely-without-email ); fi

    local IFS=',' DA
    read -ra DA <<< "$domains"
    for d in "${DA[@]}"; do args+=( -d "$d" ); done

    case "$plugin" in
        webroot)       args+=( --webroot -w "$webroot" ) ;;
        nginx)         args+=( --nginx ) ;;
        standalone)    args+=( --standalone ) ;;
        dns-cloudflare) args+=( --dns-cloudflare )
                        [ -n "$dns_creds" ] && args+=( --dns-cloudflare-credentials "$dns_creds" ) ;;
    esac
    [ "$dryrun" -eq 1 ] && args+=( --dry-run )

    echo "cert: $([ "$prod" -eq 1 ] && echo PRODUCTION || echo STAGING) issue for: $domains (plugin=$plugin)"
    certbot_run certonly "${args[@]}"
}

renew_cmd() {
    local dryrun=0
    [ "${1:-}" = "--dry-run" ] && dryrun=1
    local args=( renew )
    [ "$dryrun" -eq 1 ] && args+=( --dry-run )
    certbot_run "${args[@]}"
}

certs_cmd() {
    certbot_run certificates
}

delete_cmd() {
    local name=""
    while [ $# -gt 0 ]; do
        case "$1" in
            --domain|-d|--cert-name) name="$2"; shift 2 ;;
            --help|-h) usage; exit 0 ;;
            *) echo "cert: unknown option: $1" >&2; usage; exit 2 ;;
        esac
    done
    [ -n "$name" ] || { echo "cert: --domain is required" >&2; exit 2; }
    certbot_run delete --cert-name "$name"
}

case "${1:-}" in
    issue)        shift; issue_cmd "$@" ;;
    renew)        shift; renew_cmd "$@" ;;
    certs|list|status) certs_cmd ;;
    delete|rm)    shift; delete_cmd "$@" ;;
    --help|-h)    usage ;;
    *) usage; exit 2 ;;
esac
