#!/bin/bash

# Create systemd service file with correct Node.js path from NVM

# Source NVM to get the correct paths
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

# Get the current Node.js path
NODE_PATH=$(which node)
if [ -z "$NODE_PATH" ]; then
    echo "Error: Node.js not found. Please install Node.js via NVM first."
    exit 1
fi

echo "Creating systemd service with Node.js path: $NODE_PATH"

# Create the service file
cat > /etc/systemd/system/whp-terminal.service << EOF
[Unit]
Description=WHP WebSocket Terminal Server
After=network.target mariadb.service

[Service]
Type=simple
User=root
WorkingDirectory=/root/whp/terminal-server
ExecStart=$NODE_PATH /root/whp/terminal-server/server.js
Restart=always
RestartSec=10

# Environment variables
Environment="NODE_ENV=production"
Environment="NVM_DIR=/root/.nvm"
Environment="PATH=$NVM_DIR/versions/node/$(node -v)/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Security
NoNewPrivileges=true
PrivateTmp=true

# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=whp-terminal

[Install]
WantedBy=multi-user.target
EOF

echo "✓ Systemd service created successfully"
echo "Node.js version: $(node -v)"
echo "Node.js path: $NODE_PATH"