#!/usr/bin/env bash # scripts/deploy.sh — Publica el build de Vite de Remigración en el host. # # Lo ejecuta el runner self-hosted de Gitea (usuario root) en cada push a # master: ver .gitea/workflows/deploy.yml. También sirve a mano: # # npm ci && npm run build && ./scripts/deploy.sh # # Destino (mismo patrón que prototipo-yb01-ef.localesp.es): # /opt/remigracion/dist + vhost nginx remigracion.jumpingcrab.com (HTTP) # El vhost vive en el repo (deploy/nginx.conf) y se instala si cambia. set -euo pipefail APP_NAME="remigracion" APP_HOST="remigracion.jumpingcrab.com" DEPLOY_ROOT="/opt/remigracion" VHOST_PATH="/etc/nginx/conf.d/remigracion.jumpingcrab.com.conf" BACKUP_DIR="/var/backups/nginx" TLS_CERT_PATH="/etc/letsencrypt/live/remigracion.jumpingcrab.com/fullchain.pem" ACME_WEBROOT="/var/www/letsencrypt" usage() { echo "Usage: $0" >&2 exit 2 } log() { printf '\033[1;34m[%s]\033[0m %s\n' "$APP_NAME" "$*" } fail() { printf '\033[1;31m[%s:ERROR]\033[0m %s\n' "$APP_NAME" "$*" >&2 exit 1 } host::require_root() { if [ "$(id -u)" -ne 0 ]; then fail "hay que ejecutarlo como root (el runner self-hosted ya lo hace)" fi } host::require_tools() { local tool for tool in rsync curl nginx; do if ! command -v "$tool" >/dev/null 2>&1; then fail "falta la herramienta '$tool' en el host" fi done } artifact::require_build() { local root="$1" if [ ! -f "$root/dist/index.html" ]; then fail "falta dist/index.html — ejecuta 'npm run build' antes del deploy" fi } # El vhost sirve HTTP y HTTPS: sin certificado nginx -t fallaría. tls::require_certificate() { if [ ! -f "$TLS_CERT_PATH" ]; then fail "falta el certificado $TLS_CERT_PATH — emitelo con: certbot certonly --webroot -w $ACME_WEBROOT -d $APP_HOST --deploy-hook 'systemctl reload nginx'" fi } acme::prepare_webroot() { mkdir -p "$ACME_WEBROOT" } artifact::sync() { local root="$1" mkdir -p "$DEPLOY_ROOT/dist" rsync -a --delete "$root/dist/" "$DEPLOY_ROOT/dist/" log "build sincronizado en $DEPLOY_ROOT/dist" } # SELinux (AlmaLinux, Enforcing): nginx no puede leer /opt si el contexto no # es httpd_sys_content_t. Se persiste la regla y se etiqueta el árbol. selinux::label() { local pattern local rules if ! command -v selinuxenabled >/dev/null 2>&1; then return 0 fi if ! selinuxenabled; then return 0 fi pattern="$DEPLOY_ROOT(/.*)?" if command -v semanage >/dev/null 2>&1; then # Se captura y se compara en memoria: 'grep -q' cierra el pipe antes de # tiempo y con 'set -o pipefail' el SIGPIPE del emisor daria un falso # negativo, volviendo a ejecutar semanage -a en cada deploy. rules="$(semanage fcontext -l 2>/dev/null || true)" if [[ "$rules" != *"$pattern"* ]]; then semanage fcontext -a -t httpd_sys_content_t "$pattern" fi fi if command -v restorecon >/dev/null 2>&1; then restorecon -RF "$DEPLOY_ROOT" 2>/dev/null || true elif command -v chcon >/dev/null 2>&1; then chcon -R -t httpd_sys_content_t "$DEPLOY_ROOT" fi log "contexto SELinux aplicado a $DEPLOY_ROOT" } vhost::test() { nginx -t >/dev/null 2>&1 } # Instala el vhost del repo. Devuelve 1 si no había cambios (nada que recargar) # y aborta restaurando el anterior si nginx rechaza la configuración. vhost::install() { local root="$1" local source="$root/deploy/nginx.conf" local backup if [ ! -f "$source" ]; then fail "falta $source en el repo" fi if [ -f "$VHOST_PATH" ] && cmp -s "$source" "$VHOST_PATH"; then log "vhost sin cambios ($VHOST_PATH)" return 1 fi mkdir -p "$BACKUP_DIR" if [ -f "$VHOST_PATH" ]; then backup="$BACKUP_DIR/$(basename "$VHOST_PATH").$(date +%Y%m%d-%H%M%S)" cp -a "$VHOST_PATH" "$backup" fi install -m 0644 "$source" "$VHOST_PATH" if vhost::test; then log "vhost instalado ($VHOST_PATH)" return 0 fi if [ -n "$backup" ] && [ -f "$backup" ]; then mv -f "$backup" "$VHOST_PATH" fail "nginx rechaza la configuración nueva: restaurado el vhost anterior" fi rm -f "$VHOST_PATH" fail "nginx rechaza la configuración nueva: vhost eliminado" } nginx::reload() { systemctl reload nginx log "nginx recargado" } http::expect() { local scheme="$1" local url="$2" local expected="$3" local port="80" local attempt local code if [ "$scheme" = "https" ]; then port="443" fi # Se resuelve el dominio a loopback: prueba el vhost correcto y, en HTTPS, # la cadena y el nombre del certificado (sin -k). # nginx recarga en segundo plano: se reintenta antes de dar el deploy por fallido. for attempt in $(seq 1 15); do code="$(curl -s -o /dev/null -m 5 -w '%{http_code}' \ --resolve "$APP_HOST:$port:127.0.0.1" "$url" 2>/dev/null || true)" if [ "$code" = "$expected" ]; then return 0 fi sleep 1 done fail "esperaba $expected en $url y obtuve ${code:-sin respuesta}" } http::verify() { local headers # HTTPS valida además la cadena y el nombre del certificado (sin -k). http::expect "http" "http://$APP_HOST/" "200" http::expect "https" "https://$APP_HOST/" "200" http::expect "http" "http://$APP_HOST/robots.txt" "200" headers="$(curl -sI -m 10 --resolve "$APP_HOST:443:127.0.0.1" "https://$APP_HOST/" | tr -d '\r')" if ! grep -qi '^X-Robots-Tag:.*noindex' <<< "$headers"; then fail "falta la cabecera X-Robots-Tag: noindex en la respuesta HTTPS" fi log "verificado: HTTP y HTTPS 200, certificado válido, X-Robots-Tag: noindex" } main() { local root root="$(cd "$(dirname "$0")/.." && pwd)" host::require_root host::require_tools artifact::require_build "$root" tls::require_certificate artifact::sync "$root" acme::prepare_webroot selinux::label if vhost::install "$root"; then nginx::reload fi http::verify log "LISTO: https://$APP_HOST/ (no indexable)" } main "$@"