#!/bin/bash
set -e

echo "==============================="
echo " Installing ZeroLagHub Agent"
echo "==============================="

AGENT_DIR="/opt/zlh-agent"
BIN_PATH="$AGENT_DIR/zlh-agent"
SERVICE_PATH="/etc/systemd/system/zlh-agent.service"

echo "[1/6] Creating folders..."
mkdir -p $AGENT_DIR
mkdir -p /opt/zlh/server
mkdir -p /opt/zlh/java

echo "[2/6] Copying agent binary..."
if [ ! -f ./zlh-agent ]; then
  echo "ERROR: No zlh-agent binary found in current directory!"
  exit 1
fi

cp ./zlh-agent $BIN_PATH
chmod +x $BIN_PATH

echo "[3/6] Installing systemd service..."
cat <<EOF > $SERVICE_PATH
[Unit]
Description=ZeroLagHub Game Provisioning Agent
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=root
WorkingDirectory=$AGENT_DIR
ExecStart=$BIN_PATH
Restart=always
RestartSec=2
Environment=ZLH_AGENT_PORT=18888
Environment=ZLH_AGENT_ENV=production
LimitNPROC=infinity
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

echo "[4/6] Reloading systemd..."
systemctl daemon-reload

echo "[5/6] Enabling & starting service..."
systemctl enable zlh-agent
systemctl restart zlh-agent

echo "[6/6] Verifying agent..."
sleep 1
if systemctl is-active --quiet zlh-agent; then
  echo "✔ Agent is running"
else
  echo "✖ Agent failed to start"
  journalctl -u zlh-agent --no-pager
  exit 1
fi

echo "Agent installation complete!"
echo "==============================="
