#!/bin/sh
echo "NEXORA"
up() {
  node -e "fetch('http://127.0.0.1:3000/panel').then(r=>process.exit(r.status<500?0:1)).catch(()=>process.exit(1))"
}
if ! up; then
  if [ ! -f "/opt/nexora/package.json" ]; then
    echo "This file cannot start a server on a friend's computer."
    echo "Opening https://mcnexora.com"
    if command -v open >/dev/null 2>&1; then open "https://mcnexora.com"; elif command -v xdg-open >/dev/null 2>&1; then xdg-open "https://mcnexora.com"; fi
    exit 0
  fi
  cd "/opt/nexora" || exit 1
  echo "Starting the panel on this computer."
  npm start >/tmp/nexora-panel.log 2>&1 &
  i=0
  while [ "$i" -lt 45 ]; do
    if up; then
      break
    fi
    i=$((i + 1))
    sleep 1
  done
fi
if ! up; then
  echo "The panel did not open. Run this file again."
  exit 1
fi
if command -v open >/dev/null 2>&1; then
  open "http://127.0.0.1:3000/panel"
elif command -v xdg-open >/dev/null 2>&1; then
  xdg-open "http://127.0.0.1:3000/panel"
else
  echo "Open http://127.0.0.1:3000/panel"
fi
echo "The panel is open in your browser."
echo "Leave this window open if it started the panel."
