#!/usr/bin/env bash
set -Eeuo pipefail
umask 022
[[ $EUID -eq 0 ]] || { echo 'Run as root through sudo.' >&2; exit 1; }
[[ $# -eq 1 && -d "$1/src" && -f "$1/package.json" ]] || { echo 'Usage: sudo scripts/deploy.sh /path/to/git-checkout' >&2; exit 1; }
SOURCE=$(realpath -- "$1")
BASE=/opt/archforge-status
mkdir -p "$BASE/releases"
TMP=$(mktemp -d "$BASE/.incoming.XXXXXXXX")
trap 'rm -rf "$TMP"' EXIT
mkdir -p "$TMP/app"
rsync -a --delete --exclude='.git' --exclude='data' --exclude='backups' --exclude='.env' --exclude='node_modules' --chmod=D755,F644 "$SOURCE/" "$TMP/app/"
/usr/bin/node --check "$TMP/app/src/server.js"
/usr/bin/node --test "$TMP/app/tests/"*.test.js
if [[ -d "$BASE/app" ]]; then
  /bin/bash "$BASE/app/scripts/backup.sh"
  systemctl stop archforge-status
  SNAP="$BASE/releases/release-$(date -u +%Y%m%d-%H%M%S)"
  mv "$BASE/app" "$SNAP"
  echo "$SNAP" > "$BASE/previous-release"
fi
mv "$TMP/app" "$BASE/app"
chown -R root:root "$BASE/app"
chmod 755 "$BASE/app"
systemctl start archforge-status
sleep 2
if ! systemctl is-active --quiet archforge-status; then
  echo 'New version failed to start! Restoring previous release...' >&2
  systemctl stop archforge-status || true
  mv "$BASE/app" "$BASE/releases/failed-$(date +%s)"
  if [[ -f "$BASE/previous-release" ]]; then mv "$(cat "$BASE/previous-release")" "$BASE/app";systemctl start archforge-status; fi
  exit 1
fi
echo 'Deployment successful.'
