#!/usr/bin/env bash
#
# Install nextjs.service and fix ExecStart for your Node (nvm or NodeSource).
# Run on the server after unpack or when you get 203/EXEC (so "which node" is used).
#
# Usage (from project root on server):
#   sudo bash scripts/install_nextjs_service.sh
#
set -e

APP_ROOT="${APP_ROOT:-/var/www/boundary-fastapiandnextjs}"
UNIT_DEST="/etc/systemd/system/nextjs.service"

# Find node: current PATH (if nvm loaded), then nvm dir, then /usr/bin/node
NODE_PATH=""
if command -v node &>/dev/null; then
  NODE_PATH="$(command -v node)"
fi
if [ -z "$NODE_PATH" ] && [ -d /root/.nvm/versions/node ]; then
  NODE_PATH="$(find /root/.nvm/versions/node -path '*/bin/node' -type f -executable 2>/dev/null | sort -V | tail -1)"
fi
if [ -z "$NODE_PATH" ] && [ -x /usr/bin/node ]; then
  NODE_PATH="/usr/bin/node"
fi

if [ -z "$NODE_PATH" ]; then
  echo "Error: could not find node. Install Node 20 (e.g. nvm or NodeSource) and run again."
  exit 1
fi

echo "Using node: $NODE_PATH"
echo "Installing nextjs.service and setting ExecStart to this path..."

cp "$APP_ROOT/scripts/nextjs.service" "$UNIT_DEST"
# Replace ExecStart line so it uses the found node path (escape / in path for sed)
NODE_PATH_ESCAPED="${NODE_PATH//\//\\/}"
sed -i "s|^ExecStart=.*node server.js|ExecStart=$NODE_PATH_ESCAPED server.js|" "$UNIT_DEST"

systemctl daemon-reload
echo "Done. Start with: sudo systemctl start nextjs"
echo "Or restart: sudo systemctl restart nextjs"
