#!/bin/bash
# Ubuntu 24.04 install script for the Remote Desktop Tool.
# Run from the project root: bash deploy/ubuntu/install-ubuntu.sh [server|host]
#
#   server  -> installs Node.js + sets up the signaling server (use on the
#              machine that will run 24/7 as the relay, e.g. behind nginx)
#   host    -> installs Node.js + build tools + Electron deps, ready to run
#              the host agent (the machine you want to control remotely)
set -e

MODE="${1:-server}"

echo "== Installing Node.js (LTS via NodeSource) =="
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs

if [ "$MODE" = "server" ]; then
  echo "== Setting up signaling server =="
  cd "$(dirname "$0")/../../signaling-server"
  npm install
  echo "Signaling server dependencies installed."
  echo "Next: copy deploy/ubuntu/signaling-server.service.template to"
  echo "/etc/systemd/system/signaling-server.service (fill in INSTALL_PATH),"
  echo "then: sudo systemctl daemon-reload && sudo systemctl enable --now signaling-server"

elif [ "$MODE" = "host" ]; then
  echo "== Installing build tools for the host agent (nut-js needs X11) =="
  sudo apt update
  sudo apt install -y build-essential python3 libx11-dev libxtst-dev libpng-dev \
    libnss3 libatk1.0-0 libatk-bridge2.0-0 libgtk-3-0 libgbm1 libasound2t64

  cd "$(dirname "$0")/../../host-agent"
  npm install
  echo "Host agent dependencies installed. Start it with: npm start"
  echo ""
  echo "NOTE: Ubuntu 24.04 defaults to Wayland, but screen capture is more"
  echo "reliable under X11. If getDisplayMedia fails or shows a black"
  echo "screen, log in via 'Ubuntu on Xorg' at the login screen, or run:"
  echo "  npm start -- --ozone-platform=x11"

else
  echo "Unknown mode: $MODE (use 'server' or 'host')"
  exit 1
fi
