#!/bin/bash # Obtain a TLS certificate from Let's Encrypt for one domain. # # Usage: # sudo ./scripts/init-letsencrypt.sh my-products.ru # sudo ./scripts/init-letsencrypt.sh xn----8sbfwtmcso8g.xn--p1ai # # For IDN/Cyrillic domains, pass the punycode form (certbot requires ASCII). # If no argument is given, DOMAIN is read from .env. # Run once per domain on first deploy. set -euo pipefail # ── resolve domain ──────────────────────────────────────────────────────────── if [ -n "${1:-}" ]; then DOMAIN="$1" else if [ -f .env ]; then DOMAIN_FROM_ENV=$(grep -E '^DOMAIN=' .env | cut -d= -f2- | tr -d '"'"'" | head -1) DOMAIN="${DOMAIN:-${DOMAIN_FROM_ENV:-}}" fi fi if [ -z "${DOMAIN:-}" ]; then echo "ERROR: no domain specified." >&2 echo "Usage: $0 or set DOMAIN= in .env" >&2 exit 1 fi EMAIL="${LETSENCRYPT_EMAIL:-admin@$DOMAIN}" ACME_DIR="/var/www/certbot" echo "==> Obtaining certificate for: $DOMAIN (www.$DOMAIN)" echo " Email: $EMAIL" echo "==> Ensuring acme-challenge directory exists..." sudo mkdir -p "$ACME_DIR" sudo chmod 755 "$ACME_DIR" echo "==> Requesting certificate from Let's Encrypt..." sudo certbot certonly \ --webroot \ --webroot-path="$ACME_DIR" \ --email "$EMAIL" \ --agree-tos \ --no-eff-email \ -d "$DOMAIN" \ -d "www.$DOMAIN" echo "" echo "==> Certificate obtained for $DOMAIN" echo " /etc/letsencrypt/live/$DOMAIN/fullchain.pem" echo " /etc/letsencrypt/live/$DOMAIN/privkey.pem" echo "" echo "==> Generate nginx config and reload:" echo " sudo ./scripts/generate-nginx-conf.sh $DOMAIN" echo " sudo nginx -t && sudo systemctl reload nginx" echo "" echo "==> Auto-renewal (add to /etc/cron.d/certbot if not already present):" echo " 0 3 * * * root certbot renew --quiet && systemctl reload nginx"