#!/bin/sh
set -eu

if [ "$(id -u)" -ne 0 ]; then
  echo "Run this installer as root." >&2
  exit 1
fi

if ! command -v node >/dev/null 2>&1; then
  echo "Node.js 20 or newer is required." >&2
  exit 1
fi

node_major="$(node -p 'Number(process.versions.node.split(".")[0])')"
if [ "$node_major" -lt 20 ]; then
  echo "Node.js 20 or newer is required." >&2
  exit 1
fi

script_dir="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
install_dir="/opt/vimify-edge"
config_file="/etc/vimify-edge.env"
state_dir="/var/lib/vimify-edge"

if ! id vimify-edge >/dev/null 2>&1; then
  useradd --system --home-dir "$state_dir" --shell /usr/sbin/nologin vimify-edge
fi

install -d -m 0755 "$install_dir" "$install_dir/src"
install -m 0644 "$script_dir"/package.json "$install_dir"/package.json
install -m 0644 "$script_dir"/src/*.mjs "$install_dir"/src/
install -m 0755 "$script_dir"/vpn-status.sh "$install_dir"/vpn-status.sh
install -m 0755 "$script_dir"/install-vpn-peer.sh "$install_dir"/install-vpn-peer.sh
install -d -o vimify-edge -g vimify-edge -m 0700 "$state_dir"
install -m 0644 "$script_dir"/vimify-edge.service /etc/systemd/system/vimify-edge.service
install -m 0644 "$script_dir"/vimify-vpn-status.service /etc/systemd/system/vimify-vpn-status.service
install -m 0644 "$script_dir"/vimify-vpn-status.timer /etc/systemd/system/vimify-vpn-status.timer

if [ ! -f "$config_file" ]; then
  install -m 0600 "$script_dir"/.env.example "$config_file"
  echo "Created $config_file. Add the hotspot token, RADIUS secret, and router IP before starting Vimify Edge."
else
  echo "Kept the existing $config_file."
fi

systemctl daemon-reload
systemctl enable vimify-edge.service
systemctl enable --now vimify-vpn-status.timer
echo "Installation complete. Edit $config_file, then run: systemctl start vimify-edge"
