#!/bin/bash

# HelioHost shared-hosting Discord bot controller.
# The bot project lives at ../discord-bot (sibling of bot_control).
# Change BOT_DIR if you upload the project somewhere else.
BOT_DIR="../discord-bot"
BOT_ENTRY="src/index.js"

printf 'Content-Type: text/html\n\n'

CONTROL_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$CONTROL_DIR/$BOT_DIR" 2>/dev/null && pwd)"
BOT_NAME="discord-server-blueprint"
LOG_FILE="$CONTROL_DIR/$BOT_NAME.log"
PID_FILE="$CONTROL_DIR/$BOT_NAME.pid"

if [ -z "$PROJECT_DIR" ] || [ ! -f "$PROJECT_DIR/$BOT_ENTRY" ]; then
  echo "Bot project not found. Expected: $BOT_DIR/$BOT_ENTRY"
  exit 1
fi

# Find the Node.js executable available to the HelioHost account.
NODE_BIN="$(command -v node 2>/dev/null || true)"
if [ -z "$NODE_BIN" ]; then
  for candidate in /opt/plesk/node/*/bin/node; do
    if [ -x "$candidate" ]; then NODE_BIN="$candidate"; break; fi
  done
fi

if [ -z "$NODE_BIN" ]; then
  echo "Node.js executable not found for this account."
  exit 1
fi

running_pid=""
if [ -f "$PID_FILE" ]; then
  candidate="$(cat "$PID_FILE" 2>/dev/null)"
  if [ -n "$candidate" ] && kill -0 "$candidate" 2>/dev/null; then
    running_pid="$candidate"
  else
    rm -f "$PID_FILE"
  fi
fi

if [ "$QUERY_STRING" = "action=start" ]; then
  if [ -n "$running_pid" ]; then
    echo "$BOT_NAME is already running (PID $running_pid)."
    exit 0
  fi

  cd "$PROJECT_DIR" || exit 1
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting $BOT_NAME with $NODE_BIN" >> "$LOG_FILE"
  nohup "$NODE_BIN" "$BOT_ENTRY" >> "$LOG_FILE" 2>&1 &
  new_pid=$!
  echo "$new_pid" > "$PID_FILE"
  echo "Starting $BOT_NAME (PID $new_pid)..."
  echo '<script>setTimeout(function(){location.href="./";},1500);</script>'
  exit 0
fi

if [ "$QUERY_STRING" = "action=stop" ]; then
  if [ -n "$running_pid" ]; then
    kill "$running_pid" 2>/dev/null || true
    rm -f "$PID_FILE"
    echo "Stopping $BOT_NAME (PID $running_pid)..."
  else
    echo "$BOT_NAME is not running."
  fi
  exit 0
fi

if [ "$QUERY_STRING" = "action=clear" ]; then
  : > "$LOG_FILE"
  echo "Logs cleared."
  exit 0
fi

status="Stopped"
if [ -n "$running_pid" ]; then status="Running (PID $running_pid)"; fi

echo "<!doctype html><html><head><meta charset='utf-8'><title>Discord Bot Control</title></head><body>"
echo "<h1>$BOT_NAME</h1>"
echo "<p>Status: <strong>$status</strong></p>"
echo "<p><a href='?action=start'>Start</a> | <a href='?action=stop'>Stop</a> | <a href='?action=clear'>Clear logs</a></p>"
echo "<h2>Recent log</h2><pre>"
if [ -f "$LOG_FILE" ]; then tail -n 100 "$LOG_FILE"; else echo "No log yet."; fi
echo "</pre></body></html>"
