#!/bin/bash set -euo pipefail # Idempotent server configuration. Safe to run from CI or manually. # No secrets required — only configures firewall, certbot, and starts services. REPO_DIR="/opt/hantim" if [ "$(id -u)" -ne 0 ]; then echo "ERROR: Not running as root." exit 1 fi echo "==> Making scripts executable..." chmod +x "$REPO_DIR/scripts/"*.sh echo "==> Opening firewall ports..." firewall-cmd --permanent --add-service=http firewall-cmd --permanent --add-service=https firewall-cmd --permanent --add-port=3901/tcp firewall-cmd --reload echo "==> Setting up certbot..." mkdir -p "$REPO_DIR/docker/nginx/certbot/www" mkdir -p /etc/letsencrypt/renewal-hooks/deploy cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'HOOK' #!/bin/bash docker exec nginx nginx -s reload HOOK chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh if systemctl list-unit-files certbot-renew.timer 2>/dev/null | grep -q certbot-renew; then systemctl enable --now certbot-renew.timer else echo "0 3 * * * root certbot renew --quiet" > /etc/cron.d/certbot-renew fi echo "==> Issuing SSL certificates..." # Stop nginx if running so certbot can bind to port 80 docker stop nginx 2>/dev/null || true for conf in "$REPO_DIR"/docker/nginx/conf.d/*.conf; do # Derive cert name from config filename (e.g. timothykim.net.conf -> timothykim.net) cert_name=$(basename "$conf" .conf) domains=$(grep -oP 'server_name\s+\K[^;]+' "$conf" | tr ' ' '\n' | sort -u) if [ -z "$domains" ]; then continue fi if [ -d "/etc/letsencrypt/live/$cert_name" ]; then echo " Cert for $cert_name already exists, skipping." continue fi domain_args="" for d in $domains; do domain_args="$domain_args -d $d" done echo " Issuing cert for: $cert_name ($domains)" certbot certonly --standalone --non-interactive --agree-tos --register-unsafely-without-email --cert-name "$cert_name" $domain_args done echo "==> Starting services..." # Start nginx first (creates the shared network) cd "$REPO_DIR/docker/nginx" docker compose up -d # Start all other apps for app in "$REPO_DIR"/docker/*/; do if [ "$(basename "$app")" = "nginx" ]; then continue fi app_name=$(basename "$app") echo " Starting $app_name..." cd "$app" if ! docker compose up -d; then echo " WARNING: Failed to start $app_name (image may not exist yet). It will start on first deploy." fi done echo "==> Done."