#!/bin/bash
# Setup script for Dangerous Falls on Linux
# Run as root or with sudo from the extracted package directory

set -e

INSTALL_DIR="/opt/dangerous-falls"
SERVICE_USER="dangerous-falls"
SERVICE_FILE="dangerous-falls.service"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "==> Dangerous Falls - Linux Setup"
echo "    Install directory: $INSTALL_DIR"
echo ""

# Check for root
if [ "$EUID" -ne 0 ]; then
    echo "ERROR: Please run as root (sudo bash setup-linux.sh)"
    exit 1
fi

# Check Node.js
if ! command -v node &>/dev/null; then
    echo "ERROR: Node.js is not installed."
    echo "  Install it with: sudo apt install nodejs npm  (Debian/Ubuntu)"
    echo "               or: sudo dnf install nodejs npm  (RHEL/Fedora)"
    exit 1
fi
NODE_VERSION=$(node --version)
echo "==> Node.js found: $NODE_VERSION"

# Create service user if not exists
if ! id "$SERVICE_USER" &>/dev/null; then
    echo "==> Creating service user: $SERVICE_USER"
    useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER"
fi

# Install application files
echo "==> Installing to $INSTALL_DIR ..."
rm -rf "$INSTALL_DIR"
mkdir -p "$INSTALL_DIR"
cp -r "$SCRIPT_DIR/server" "$INSTALL_DIR/"
cp -r "$SCRIPT_DIR/public" "$INSTALL_DIR/"

# Install Node dependencies
echo "==> Installing Node.js dependencies ..."
cd "$INSTALL_DIR/server"
npm install --omit=dev

# Set up .env if not already present
if [ ! -f "$INSTALL_DIR/server/.env" ]; then
    echo "==> Creating default .env ..."
    cp "$SCRIPT_DIR/.env.example" "$INSTALL_DIR/server/.env"
    # Generate a random JWT secret
    JWT_SECRET=$(node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")
    sed -i "s/change-this-to-a-random-secret-key/$JWT_SECRET/" "$INSTALL_DIR/server/.env"
    echo "    JWT_SECRET auto-generated."
    echo "    IMPORTANT: Edit $INSTALL_DIR/server/.env to set ADMIN_PASSWORD"
fi

# Fix ownership
chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_DIR"

# Install and enable systemd service
echo "==> Installing systemd service ..."
cp "$SCRIPT_DIR/$SERVICE_FILE" /etc/systemd/system/
systemctl daemon-reload
systemctl enable dangerous-falls
systemctl restart dangerous-falls

echo ""
echo "==> Setup complete!"
echo ""
echo "Service status:"
systemctl status dangerous-falls --no-pager -l
echo ""
echo "Access the game at: http://$(hostname -I | awk '{print $1}'):3010"
echo ""
echo "Useful commands:"
echo "  sudo systemctl status dangerous-falls    # Check status"
echo "  sudo systemctl restart dangerous-falls   # Restart"
echo "  sudo journalctl -u dangerous-falls -f    # View logs"
echo "  sudo nano $INSTALL_DIR/server/.env       # Edit config"
echo ""
echo "REMINDER: Change ADMIN_PASSWORD in $INSTALL_DIR/server/.env and restart the service."
