Files
dh-inspeccion-v2/scripts/install-auto-deploy.sh
T

105 lines
2.7 KiB
Bash

#!/usr/bin/env bash
set -Eeuo pipefail
APP="/var/www/dhv2.korexlabs.com"
KEY="/root/.ssh/dhv2_github"
WATCHER="/usr/local/sbin/dhv2-auto-deploy"
SERVICE="/etc/systemd/system/dhv2-auto-deploy.service"
TIMER="/etc/systemd/system/dhv2-auto-deploy.timer"
if [ "$(id -u)" -ne 0 ]; then
echo "ERROR: ejecutar como root."
exit 1
fi
cd "$APP"
[ -d .git ] || { echo "ERROR: $APP no es repositorio Git."; exit 1; }
[ -f "$KEY" ] || { echo "ERROR: falta $KEY"; exit 1; }
git config --global --add safe.directory "$APP" >/dev/null 2>&1 || true
git config core.sshCommand "ssh -i $KEY -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"
cat > "$WATCHER" <<'WATCH'
#!/usr/bin/env bash
set -Eeuo pipefail
APP="/var/www/dhv2.korexlabs.com"
KEY="/root/.ssh/dhv2_github"
LOCK="/var/lock/dhv2-auto-deploy.lock"
exec 9>"$LOCK"
flock -n 9 || exit 0
cd "$APP"
export GIT_SSH_COMMAND="ssh -i $KEY -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new"
git config --global --add safe.directory "$APP" >/dev/null 2>&1 || true
if ! git fetch --quiet origin deploy; then
echo "No se pudo consultar origin/deploy; producción no se modifica."
exit 0
fi
TARGET="$(git rev-parse origin/deploy)"
CURRENT="$(git rev-parse HEAD)"
[ "$TARGET" != "$CURRENT" ] || exit 0
if ! git merge-base --is-ancestor "$CURRENT" "$TARGET"; then
echo "ERROR: origin/deploy no es fast-forward desde $CURRENT. Deploy rechazado."
exit 1
fi
TMP="$(mktemp /root/dhv2-deploy.XXXXXX.sh)"
trap 'rm -f "$TMP"' EXIT
git show "$TARGET:scripts/deploy-github.sh" > "$TMP"
chmod 700 "$TMP"
DHV2_DEPLOY_REF=deploy bash "$TMP"
WATCH
chmod 700 "$WATCHER"
cat > "$SERVICE" <<'UNIT'
[Unit]
Description=DH V2 autonomous GitHub deploy check
After=network-online.target docker.service
Wants=network-online.target
Requires=docker.service
[Service]
Type=oneshot
User=root
WorkingDirectory=/var/www/dhv2.korexlabs.com
ExecStart=/usr/local/sbin/dhv2-auto-deploy
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=6
UNIT
cat > "$TIMER" <<'UNIT'
[Unit]
Description=Check DH V2 deploy branch every minute
[Timer]
OnBootSec=45s
OnUnitInactiveSec=60s
AccuracySec=10s
Persistent=true
Unit=dhv2-auto-deploy.service
[Install]
WantedBy=timers.target
UNIT
systemctl daemon-reload
systemctl enable --now dhv2-auto-deploy.timer
echo
echo "============================================================"
echo " DH V2 AUTO-DEPLOY INSTALADO"
echo "============================================================"
echo "Watcher: $WATCHER"
echo "Timer: dhv2-auto-deploy.timer"
echo "Logs: journalctl -u dhv2-auto-deploy.service"
echo "============================================================"
systemctl --no-pager --full status dhv2-auto-deploy.timer | sed -n '1,16p' || true