#!/usr/bin/env bash
set -euo pipefail
[ "$(id -u)" -eq 0 ] || { echo "run with sudo" >&2; exit 1; }
f="${1:?usage: trinity-import <file.wspx> [--force]}"; shift || true
E=/etc/trinity; cluster=0
if [ -f /etc/systemd/system/trinity-portal.service.d/cluster.conf ]; then
  cluster=1; E=/var/lib/trinity/etc
  mountpoint -q /var/lib/trinity && [ -f "$E/trinity.json" ] || { echo "the shared folder is not mounted here - run trinity-import on the active node (sudo pcs status)" >&2; exit 1; }
fi
tmp=$(mktemp -d); cp "$f" "$tmp/import.wspx"; chown -R trinity:trinity "$tmp"
SVC=trinity-svc; [ $cluster -eq 1 ] && ! pcs resource config trinity-svc >/dev/null 2>&1 && pcs resource config wsp-svc >/dev/null 2>&1 && SVC=wsp-svc
if [ $cluster -eq 1 ]; then
  pcs resource disable $SVC --wait=120 >/dev/null || { echo "could not stop $SVC (pcs status)" >&2; exit 1; }
else systemctl stop trinity-portal || true; fi
set +e
sudo -u trinity env WSP_DATA=/var/lib/trinity WSP_CONFIG="$E/trinity.json" WSP_SECRET_KEY="$E/secret.key" ${WSP_IMPORT_PASSPHRASE:+WSP_IMPORT_PASSPHRASE="$WSP_IMPORT_PASSPHRASE"} \
    /opt/trinity/app/trinity-portal import "$tmp/import.wspx" "$@"
rc=$?
set -e
rm -rf "$tmp"
if [ $cluster -eq 1 ]; then
  chown -R trinity:trinity /var/lib/trinity/App_Data /var/lib/trinity/reports 2>/dev/null || true
  pcs resource enable $SVC
  echo "$SVC enabled again - the portal starts on the active node (sudo pcs status)"
else
  chown -R trinity:trinity /var/lib/trinity
  systemctl start trinity-portal
fi
exit $rc
