#!/bin/sh
set -eu
if [ "$(id -u)" -ne 0 ]; then
    echo "Run with sudo or as root." >&2
    exit 1
fi
here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
node_bin=${SCALPING_NODE_BIN:-$(command -v node || true)}
case "$node_bin" in
    /*) ;;
    *) echo "Install Node.js 24 and make it available to the service." >&2; exit 1 ;;
esac
case "$node_bin" in
    *[!A-Za-z0-9_./-]*) echo "Use a system Node executable path without spaces." >&2; exit 1 ;;
esac
case "$(readlink -f "$node_bin")" in
    /root/*|/home/*) echo "Use a system Node executable outside home directories." >&2; exit 1 ;;
esac
"$node_bin" -e "if (!process.versions.node.startsWith('24.')) process.exit(1); require('node:sqlite');" ||
    { echo "Node.js 24 with node:sqlite is required by this package." >&2; exit 1; }
command -v systemctl >/dev/null || { echo "This installer requires systemd." >&2; exit 1; }

if ! id scalping-space >/dev/null 2>&1; then
    useradd --system --user-group --home-dir /var/lib/scalping-space --shell "$(command -v nologin)" scalping-space
fi
install -d -m 0755 /opt/scalping-space/app/academy
install -d -m 0700 -o scalping-space -g scalping-space /var/lib/scalping-space
for name in server.mjs auth.mjs backup.mjs notifications.mjs markets.mjs Scalping-Space-Review.html scalping-space-mark.svg; do
    install -m 0644 "$here/app/$name" "/opt/scalping-space/app/$name"
done
for resource in "$here"/app/academy/*.pdf; do
    install -m 0644 "$resource" /opt/scalping-space/app/academy/
done
if [ ! -f /etc/scalping-space.env ]; then
    install -m 0600 "$here/deploy/scalping-space.env.example" /etc/scalping-space.env
fi
sed "s|@NODE@|$node_bin|" "$here/deploy/scalping-space.service" >/etc/systemd/system/scalping-space.service
systemctl daemon-reload
systemctl enable scalping-space.service
systemctl restart scalping-space.service
systemctl --no-pager status scalping-space.service
