#!/bin/sh
# Root-owned deploy step, installed as /usr/local/sbin/workshare-deploy by setup-ci-deploy.sh.
#   sudo /usr/local/sbin/workshare-deploy <40-hex commit>
# Fetches that commit into the root-owned clone /opt/workshare-src, runs the tests as an unprivileged user,
# then runs that commit's deploy/linux/update.sh (backup, install, health check, automatic rollback).
set -eu
SRC=/opt/workshare-src
SHA="${1:-}"
case "$SHA" in *[!0-9a-f]*|"") echo "usage: workshare-deploy <commit sha>"; exit 2 ;; esac
[ "${#SHA}" -eq 40 ] || { echo "commit must be the full 40-character sha"; exit 2; }
[ -d "$SRC/.git" ] || { echo "$SRC is not set up (run setup-ci-deploy.sh)"; exit 1; }

exec 9>/run/workshare-deploy.lock
flock -n 9 || { echo "another deploy is running"; exit 1; }

echo "== fetching $SHA"
cd "$SRC"
git fetch --quiet origin
git cat-file -e "$SHA^{commit}" 2>/dev/null || { echo "commit $SHA not found on origin"; exit 1; }
git checkout --quiet --force --detach "$SHA"
git clean -qfdx

echo "== tests"
TMPT="$(mktemp -d)"; cp -r "$SRC/src" "$SRC/test" "$SRC/tools" "$SRC/deploy" "$SRC/package.json" "$TMPT/"; chmod -R a+rX "$TMPT"
if ! runuser -u nobody -- sh -c "cd '$TMPT' && HOME=/tmp TMPDIR=/tmp node test/workshare-test.js >/dev/null && node test/central-test.js >/dev/null && node test/production-test.js >/dev/null && node test/storage-test.js >/dev/null && node test/appversion-test.js >/dev/null && node test/pg-driver-test.js >/dev/null && node test/db-store-test.js >/dev/null"; then
  rm -rf "$TMPT"; echo "tests failed on the server, nothing deployed"; exit 1
fi
rm -rf "$TMPT"

echo "== installing"
sh deploy/linux/update.sh
echo "deployed $SHA"
