#!/bin/bash

# Standalone dashboard launcher.
# Uses the Node.js runtime bundled in ./node when present, falling back to a
# system-wide Node.js install for packages that don't include a runtime.

REQUIRED_VERSION="22.12.0"
DOWNLOAD_URL="https://whitestar.io/downloads/dashboard"

check_for_update() {
  echo -e "🔄 \033[36mChecking for updates...\033[0m"
  REMOTE_VERSION=$(curl -fs "$DOWNLOAD_URL/release.txt")
  LOCAL_VERSION=$(cat ./release.txt 2>/dev/null || echo "0")

  case "$REMOTE_VERSION" in
    ''|*[!0-9]*)
      echo -e "⚠️  \033[33mCould not check for updates (network error)\033[0m"
      return
      ;;
  esac

  if [ "$REMOTE_VERSION" -le "$LOCAL_VERSION" ]; then
    echo -e "✅ \033[32mYou are running the latest version (v$LOCAL_VERSION)\033[0m"
    return
  fi

  echo -e "📬 \033[32mAn update is available! (v$REMOTE_VERSION > v$LOCAL_VERSION)\033[0m"
  if [ -z "$PLATFORM" ]; then
    echo -e "⚠️  \033[33mAutomatic updates are not supported on this platform ($(uname -s) $(uname -m)). Download it manually from $DOWNLOAD_URL\033[0m"
    return
  fi

  read -p "Would you like to download and install the update now? (y/n) " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    return
  fi

  echo -e "📥 \033[36mDownloading update...\033[0m"
  UPDATE_ARCHIVE=$(mktemp "${TMPDIR:-/tmp}/dashboard-update-XXXXXX")
  if curl -fL "$DOWNLOAD_URL/dashboard-$PLATFORM.tar.gz" -o "$UPDATE_ARCHIVE"; then
    echo -e "📦 \033[36mExtracting update...\033[0m"
    tar -xzf "$UPDATE_ARCHIVE" -C "$SCRIPT_DIR"
    rm -f "$UPDATE_ARCHIVE"
    echo -e "✅ \033[32mUpdate installed successfully! Restarting...\033[0m"
    exec /bin/bash "$SCRIPT_DIR/start.sh"
  else
    rm -f "$UPDATE_ARCHIVE"
    echo -e "❌ \033[31mFailed to download update\033[0m"
  fi
}

main() {
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  cd "$SCRIPT_DIR"

  # Platform suffix of the release package to use for self-updates
  case "$(uname -s)-$(uname -m)" in
    Linux-x86_64)              PLATFORM="linux-x64" ;;
    Linux-aarch64|Linux-arm64) PLATFORM="linux-arm64" ;;
    Darwin-arm64)              PLATFORM="darwin-arm64" ;;
    Darwin-x86_64)             PLATFORM="darwin-x64" ;;
    *)                         PLATFORM="" ;;
  esac

  # Prefer the bundled Node.js runtime; otherwise require a recent system Node.js
  if [ -x "$SCRIPT_DIR/node/bin/node" ]; then
    # Put the bundled runtime first on PATH so npm lifecycle scripts that
    # spawn "node" also use it
    export PATH="$SCRIPT_DIR/node/bin:$PATH"
    NODE_BIN="$SCRIPT_DIR/node/bin/node"
  elif command -v node >/dev/null 2>&1; then
    NODE_BIN="$(command -v node)"
    NODE_VERSION=$("$NODE_BIN" -v | cut -d'v' -f2)
    if [ "$(printf '%s\n' "$REQUIRED_VERSION" "$NODE_VERSION" | sort -V | head -n1)" != "$REQUIRED_VERSION" ]; then
      echo -e "❌ \033[31mNode.js version $NODE_VERSION is not supported. Please update to v$REQUIRED_VERSION or later, or download the package for your platform (which includes Node.js) from $DOWNLOAD_URL\033[0m"
      exit 1
    fi
  else
    echo -e "❌ \033[31mNode.js is not installed. Download the package for your platform (which includes Node.js) from $DOWNLOAD_URL\033[0m"
    exit 1
  fi

  # Use the npm that ships with the bundled runtime when available
  if [ -f "$SCRIPT_DIR/node/lib/node_modules/npm/bin/npm-cli.js" ]; then
    NPM=("$NODE_BIN" "$SCRIPT_DIR/node/lib/node_modules/npm/bin/npm-cli.js")
  else
    NPM=(npm)
  fi

  # If node_modules folder does not exist, run npm install
  if [ ! -d node_modules ]; then
    echo "📦 node_modules folder does not exist. Running npm install..."
    if ! "${NPM[@]}" install; then
      echo -e "❌ \033[31mnpm install failed. See the output above for details.\033[0m"
      exit 1
    fi
    echo "✅ npm install completed"
  fi

  # First run: create the local database from the bundled default
  if [ ! -f packages/standalone/dashboard.db ] && [ -f packages/standalone/default-database.db ]; then
    echo "🗄️  Creating dashboard.db from the default database..."
    cp packages/standalone/default-database.db packages/standalone/dashboard.db
  fi

  check_for_update

  echo -e "🚀 \033[36mStarting server...\033[0m"
  HOSTNAME=0.0.0.0 exec "$NODE_BIN" ./packages/standalone/server.js
}

main "$@"
