#!/bin/sh
set -eu

APP_DOMAIN="${APP_DOMAIN:-}"
APP_WWW_DOMAIN="${APP_WWW_DOMAIN:-}"
ACME_EMAIL="${ACME_EMAIL:-}"
CERTBOT_STAGING="${CERTBOT_STAGING:-0}"
CERTBOT_RENEW_INTERVAL="${CERTBOT_RENEW_INTERVAL:-12h}"

if [ -z "$APP_DOMAIN" ] || [ -z "$ACME_EMAIL" ]; then
  echo "Skipping certbot: APP_DOMAIN or ACME_EMAIL is empty."
  exit 0
fi

(
  sleep 20

  if [ ! -f "/etc/letsencrypt/renewal/$APP_DOMAIN.conf" ]; then
    rm -rf "/etc/letsencrypt/live/$APP_DOMAIN" "/etc/letsencrypt/archive/$APP_DOMAIN"
  fi

  while :; do
    DOMAINS="-d $APP_DOMAIN"
    if [ -n "$APP_WWW_DOMAIN" ]; then
      DOMAINS="$DOMAINS -d $APP_WWW_DOMAIN"
    fi

    STAGING_FLAG=""
    if [ "$CERTBOT_STAGING" = "1" ]; then
      STAGING_FLAG="--staging"
    fi

    # shellcheck disable=SC2086
    certbot certonly \
      --webroot \
      -w /var/www/certbot \
      --agree-tos \
      --non-interactive \
      --email "$ACME_EMAIL" \
      --keep-until-expiring \
      $STAGING_FLAG \
      $DOMAINS || true

    nginx -s reload || true
    sleep "$CERTBOT_RENEW_INTERVAL"
  done
) &
