#!/bin/bash # Obtain TLS certificates from Let's Encrypt. # Run once on first deploy: sudo ./scripts/init-letsencrypt.sh # Requires nginx running on the host with acme-challenge location configured. # Set DOMAIN in .env or export it before running: # DOMAIN=example.com sudo -E ./scripts/init-letsencrypt.sh set -euo pipefail # Load DOMAIN from .env if not already set in environment if [ -f .env ]; then # Extract DOMAIN line, strip quotes and export DOMAIN_FROM_ENV=$(grep -E '^DOMAIN=' .env | cut -d= -f2- | tr -d '"'"'" | head -1) DOMAIN="${DOMAIN:-$DOMAIN_FROM_ENV}" fi if [ -z "${DOMAIN:-}" ]; then echo "ERROR: DOMAIN is not set. Add DOMAIN=yourdomain.com to .env or export it." >&2 exit 1 fi EMAIL="${LETSENCRYPT_EMAIL:-admin@$DOMAIN}" CERTBOT_DIR="./certbot" ACME_DIR="/var/www/certbot" echo "==> Creating certbot directories..." mkdir -p "$CERTBOT_DIR/conf" "$CERTBOT_DIR/www" echo "==> Ensuring acme-challenge directory exists on host..." 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 "==> Copying certificates to project directory..." sudo cp "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" "$CERTBOT_DIR/conf/fullchain.pem" sudo cp "/etc/letsencrypt/live/$DOMAIN/privkey.pem" "$CERTBOT_DIR/conf/privkey.pem" sudo chown "$(whoami):$(whoami)" "$CERTBOT_DIR/conf"/*.pem echo "==> Done! TLS certificate installed for $DOMAIN" echo "" echo "Regenerate nginx config from template:" echo " DOMAIN=$DOMAIN envsubst '\$DOMAIN' < nginx/nginx.conf.template > nginx/nginx.conf" echo "" echo "Certificate files:" echo " - $CERTBOT_DIR/conf/fullchain.pem" echo " - $CERTBOT_DIR/conf/privkey.pem" echo "" echo "Configure nginx:" echo " ssl_certificate $CERTBOT_DIR/conf/fullchain.pem;" echo " ssl_certificate_key $CERTBOT_DIR/conf/privkey.pem;" echo "" echo "Set up auto-renewal with: sudo crontab -e" echo "Add: 0 3 * * * certbot renew --quiet && systemctl reload nginx"