#!/bin/bash # Helpdesk production deploy. Installed once at /usr/local/sbin/helpdesk-deploy (root-owned); the CI # deploy job runs it via `sudo` (gitlab-runner has a scoped NOPASSWD entry for exactly this path). # It syncs a checkout into /srv/helpdesk, runs the idempotent migration, restarts the service, polls # health, and rolls back to the previous release if health fails. # usage: helpdesk-deploy set -euo pipefail SRC="${1:?usage: helpdesk-deploy }" DEST=/srv/helpdesk PREV=/srv/helpdesk.prev ENVFILE=/etc/helpdesk/env HEALTH=http://127.0.0.1:4000/healthz echo "[deploy] from $SRC -> $DEST" # 1) snapshot current release for rollback rm -rf "$PREV" [ -d "$DEST" ] && cp -a "$DEST" "$PREV" # 2) sync new code (never copy VCS metadata or local secrets) rsync -a --delete --exclude='.git/' --exclude='.claude/' "$SRC"/ "$DEST"/ # 3) idempotent schema migration, as the least-privilege helpdesk role from the env file DBURL="$(sed -n 's/^HELPDESK_DATABASE_URL=//p' "$ENVFILE")" psql "$DBURL" -q -f "$DEST/components/backend/db/migrate/001_init.sql" # 4) restart + health poll systemctl restart helpdesk.service healthy=0 for _ in $(seq 1 15); do sleep 1 if curl -fsS -m3 "$HEALTH" >/dev/null 2>&1; then healthy=1; break; fi done if [ "$healthy" = 1 ]; then echo "[deploy] healthy after restart — done" rm -rf "$PREV" exit 0 fi # 5) rollback echo "[deploy] HEALTH CHECK FAILED — rolling back to previous release" if [ -d "$PREV" ]; then rm -rf "$DEST" mv "$PREV" "$DEST" systemctl restart helpdesk.service echo "[deploy] rolled back" fi exit 1