#!/usr/bin/env bash set -e GREEN='\033[0;32m' RED='\033[0;31m' YELLOW='\033[1;33m' NC='\033[0m' if [ ! -f ".env" ]; then echo -e "${RED}[ERROR] .env file not found. Skipping SSL setup.${NC}" exit 1 fi source .env SSL_MODE="${SSL_MODE:-none}" NGINX_CONF_DIR="./nginx/conf.d" NGINX_SSL_DIR="./nginx/ssl" mkdir -p "$NGINX_CONF_DIR" "$NGINX_SSL_DIR" # ── Helper: write HTTP-only config ── write_http_conf() { cat > "$NGINX_CONF_DIR/gitea.conf" <<'NGINX' server { listen 80; server_name _; location / { proxy_pass http://gitea:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; client_max_body_size 512M; } } NGINX } # ── Helper: write HTTPS config (works for both letsencrypt & custom) ── write_https_conf() { local cert_path="$1" local key_path="$2" cat > "$NGINX_CONF_DIR/gitea.conf" </dev/null 2>&1 && \ docker run --rm -v gitea-deployment_certbot_certs:/etc/letsencrypt alpine \ test -f "/etc/letsencrypt/live/${GITEA_DOMAIN}/fullchain.pem" 2>/dev/null; then echo "[SSL] Existing Let's Encrypt certs found. Writing HTTPS config." write_https_conf "$CERT" "$KEY" else echo "[SSL] No certs yet. Writing temporary HTTP config for ACME challenge." write_http_conf fi ;; custom) echo -e "${GREEN}[SSL] Mode: custom${NC}" if [[ -z "$SSL_CERT_PATH" || -z "$SSL_KEY_PATH" ]]; then echo -e "${RED}[ERROR] SSL_CERT_PATH and SSL_KEY_PATH are required for custom mode.${NC}" exit 1 fi if [[ ! -f "$SSL_CERT_PATH" ]]; then echo -e "${RED}[ERROR] Certificate not found: $SSL_CERT_PATH${NC}" exit 1 fi if [[ ! -f "$SSL_KEY_PATH" ]]; then echo -e "${RED}[ERROR] Key not found: $SSL_KEY_PATH${NC}" exit 1 fi cp "$SSL_CERT_PATH" "$NGINX_SSL_DIR/cert.pem" cp "$SSL_KEY_PATH" "$NGINX_SSL_DIR/key.pem" chmod 600 "$NGINX_SSL_DIR/key.pem" write_https_conf "/etc/nginx/ssl/cert.pem" "/etc/nginx/ssl/key.pem" echo -e "${GREEN}[SSL] Custom certificates copied to $NGINX_SSL_DIR${NC}" ;; *) echo -e "${RED}[ERROR] Unknown SSL_MODE: $SSL_MODE (expected: none, letsencrypt, custom)${NC}" exit 1 ;; esac echo -e "${GREEN}[SSL] Nginx config written to $NGINX_CONF_DIR/gitea.conf${NC}"