#!/bin/sh
# Install / update the service on the piler host. Run from the repo:
#   sh reference/mail-archive-api/install.sh [root@192.168.9.53]
# Keeps an existing /opt/logship-mail-archive/.env (token); creates one on first install.
set -e
HOST="${1:-root@192.168.9.53}"
DIR=/opt/logship-mail-archive
HERE="$(cd "$(dirname "$0")" && pwd)"
ssh "$HOST" "mkdir -p $DIR"
scp -q "$HERE/server.mjs" "$HERE/package.json" "$HOST:$DIR/"
scp -q "$HERE/logship-mail-archive.service" "$HOST:/etc/systemd/system/logship-mail-archive.service"
ssh "$HOST" "cd $DIR && npm install --omit=dev --no-audit --no-fund >/dev/null \
  && { [ -f .env ] || { umask 077; printf 'PORT=8097\nPILER_UID=5\nMAIL_ARCHIVE_TOKEN=%s\n' \"\$(openssl rand -hex 32)\" > .env; }; } \
  && { grep -q '^PILER_UID=' .env || echo 'PILER_UID=5' >> .env; } \
  && chown root:piler .env && chmod 640 .env \
  && systemctl daemon-reload && systemctl enable -q logship-mail-archive && systemctl restart logship-mail-archive \
  && sleep 1 && systemctl is-active logship-mail-archive && curl -s http://127.0.0.1:8097/health && echo"
echo "Token (→ MAIL_ARCHIVE_TOKEN in the ERP .env):"
ssh "$HOST" "grep ^MAIL_ARCHIVE_TOKEN= $DIR/.env | cut -d= -f2"
