refactor(scripts): lib de despliegue OOP (Env + colaboradores)
deploy-branch / deploy (push) Successful in 2m14s
deploy-branch / teardown (push) Skipped

- scripts/lib/env.sh: modelo OOP. Env (aggregate root) compone las entidades
  SystemdUnit, NginxVhost y TlsCert, más servicios estáticos (Slug, Host,
  Port, Artifacts, Deps, Logger). Instancias = arrays asociativos globales
  accedidos vía nameref (local -n); la composición vive en Env::new.
- deploy.sh / teardown.sh: pasan a ser entrypoints finos (~33 líneas) que
  sourcean lib/env.sh. Comparten una única fuente de verdad para "qué es un
  entorno", eliminando la duplicación de slugify y el regex de vhost.
- Comportamiento idéntico al procedural: heredocs de systemd/nginx son
  byte-idénticos; orquestación de deploy y teardown verificados end-to-end.

Requiere bash >= 4.3 (namerefs), ya cubierto en el host runner.
This commit is contained in:
2026-08-01 18:08:01 +02:00
parent 6323fe8f0e
commit 6cc326e8ac
3 changed files with 494 additions and 168 deletions
+22 -26
View File
@@ -1,37 +1,33 @@
#!/usr/bin/env bash
# teardown.sh — Elimina el entorno de una rama (al borrar la rama o a mano).
# usage: teardown.sh <branch>
# Toda la lógica vive en lib/env.sh (modelo OOP). Éste es sólo el entrypoint.
set -euo pipefail
BRANCH="${1:?usage: $0 <branch>}"
DOMAIN="localesp.es"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/env.sh
. "$SCRIPT_DIR/lib/env.sh"
log() { printf '\033[1;34m[teardown]\033[0m %s\n' "$*"; }
usage() {
echo "usage: $0 <branch>" >&2
exit 2
}
slugify() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+//; s/-+$//'; }
SLUG="$(slugify "$BRANCH")"
UNIT="localesp-$SLUG"
HOST="$SLUG.$DOMAIN"
DEST="/opt/localesp/$SLUG"
main() {
local branch root
log "$HOST ($DEST, $UNIT)"
branch="${1:-}"
if [ -z "$branch" ]; then
usage
fi
root="$(cd "$SCRIPT_DIR/.." && pwd)"
systemctl disable --now "$UNIT" 2>/dev/null || true
rm -f "/etc/systemd/system/$UNIT.service"
systemctl daemon-reload
Logger::set_tag teardown
Env::new env "$branch" "$root"
Logger::info "$(Env::identity env)"
if [ -d "/etc/letsencrypt/live/$HOST" ]; then
log "borrando cert $HOST"
certbot delete --cert-name "$HOST" -n 2>/dev/null || true
fi
Env::teardown env
HOST_RE="$(printf '%s' "$HOST" | sed 's/\./\\./g')"
VHOST="$(grep -rlE "server_name[[:space:]]+$HOST_RE[[:space:]]*;" /etc/nginx/conf.d/*.conf 2>/dev/null | head -1 || true)"
if [ -n "$VHOST" ]; then
log "borrando vhost $VHOST"
rm -f "$VHOST"
nginx -t && systemctl reload nginx
fi
Logger::info "entorno eliminado ✓"
}
rm -rf "$DEST"
log "entorno eliminado ✓"
main "$@"