spark-server/deploy/nginx/install-host.sh
2026-09-18 14:50:41 +08:00

84 lines
2.2 KiB
Bash
Executable File

#!/usr/bin/env bash
# Install Spark SNI vhosts into the shared host nginx (do not replace nginx.conf).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
HOST_DIR="$ROOT/host"
BACKUP="/root/nginx-backup-$(date +%Y%m%d%H%M%S)"
need_certs() {
[[ -f /etc/letsencrypt/live/sparkapi.wyrs365.com/fullchain.pem ]] \
&& [[ -f /etc/letsencrypt/live/sparkim.wyrs365.com/fullchain.pem ]]
}
install_acme() {
mkdir -p /var/www/certbot
cp "$HOST_DIR/spark-acme.conf" /etc/nginx/conf.d/spark-acme.conf
nginx -t
systemctl reload nginx
}
issue_certs() {
certbot certonly --webroot -w /var/www/certbot \
--non-interactive --agree-tos --keep-until-expiring \
-d sparkapi.wyrs365.com
certbot certonly --webroot -w /var/www/certbot \
--non-interactive --agree-tos --keep-until-expiring \
-d sparkim.wyrs365.com
}
rewrite_http_443() {
local f
for f in /etc/nginx/conf.d/*.conf; do
case "$(basename "$f")" in
sparkapi.conf|spark-acme.conf) continue ;;
esac
if grep -qE 'listen[[:space:]]+127\.0\.0\.1:8443' "$f"; then
continue
fi
if grep -qE 'listen[[:space:]]+443[[:space:]]+ssl' "$f"; then
sed -i \
-e 's/listen 443 ssl;/listen 127.0.0.1:8443 ssl proxy_protocol;/' \
-e 's/listen \[::\]:443 ssl;/listen [::1]:8443 ssl proxy_protocol;/' \
"$f"
fi
done
}
install_sni() {
rewrite_http_443
rm -f /etc/nginx/conf.d/spark-acme.conf
cp "$HOST_DIR/00-spark-http.conf" /etc/nginx/conf.d/00-spark-http.conf
cp "$HOST_DIR/sparkapi.conf" /etc/nginx/conf.d/sparkapi.conf
cp "$HOST_DIR/spark-sni.conf" /etc/nginx/stream.d/spark-sni.conf
mkdir -p /etc/letsencrypt/renewal-hooks/deploy
cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'HOOK'
#!/bin/sh
systemctl reload nginx
HOOK
chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh
if grep -RInE 'listen[[:space:]]+(\[::\]:)?443[[:space:]]+ssl' /etc/nginx/conf.d; then
echo "http still binds public 443" >&2
exit 1
fi
nginx -t
systemctl reload nginx
}
mkdir -p "$BACKUP"
cp -a /etc/nginx "$BACKUP/nginx"
echo "backup $BACKUP"
if ! need_certs; then
install_acme
issue_certs
fi
if ! need_certs; then
echo "certificates missing" >&2
exit 1
fi
install_sni
echo "nginx sni ready"