#!/bin/sh
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
NODE="$ROOT/node/bin/node"
SCRIPT="$ROOT/src/server.js"
URL="http://127.0.0.1:47323/"
CONFIG="${HOME}/.config/KeyBridge"
PROFILE="$CONFIG/window"
PIDFILE="$CONFIG/node.pid"
LOG="$CONFIG/session.log"

if [ ! -x "$NODE" ]; then
  echo "KeyBridge Platform is missing a file. Download it again from https://www.keyplatform.org"
  exit 1
fi

mkdir -p "$CONFIG" "$PROFILE"
: > "$PROFILE/First Run"
: > "$PROFILE/FirstLaunchAfterInstallation"

page_up() {
  "$NODE" -e 'const http=require("http");const u=process.argv[1];const req=http.get(u,function(r){r.resume();process.exit(r.statusCode===200?0:1);});req.on("error",function(){process.exit(1);});req.setTimeout(800,function(){req.destroy();process.exit(1);});' "$URL"
}

open_browser() {
  browser=""
  for name in google-chrome google-chrome-stable chromium chromium-browser microsoft-edge microsoft-edge-stable; do
    if command -v "$name" >/dev/null 2>&1; then
      browser=$name
      break
    fi
  done
  if [ -n "$browser" ]; then
    "$browser" --app="$URL" --user-data-dir="$PROFILE" --no-proxy-server --no-first-run --no-default-browser-check --disable-extensions --window-size=1120,800 >/dev/null 2>&1 &
    return
  fi
  if command -v firefox >/dev/null 2>&1; then
    firefox --no-remote --new-instance --profile "$PROFILE" "$URL" >/dev/null 2>&1 &
    return
  fi
  if command -v xdg-open >/dev/null 2>&1; then
    xdg-open "$URL" >/dev/null 2>&1 &
  fi
}

if page_up; then
  open_browser
  exit 0
fi

if [ -f "$PIDFILE" ]; then
  old=$(cat "$PIDFILE" 2>/dev/null || true)
  if [ -n "$old" ]; then
    kill "$old" 2>/dev/null || true
    sleep 0.3
  fi
fi

PORT=47323 NO_BROWSER=1 nohup "$NODE" "$SCRIPT" >"$LOG" 2>&1 &
NODE_PID=$!
echo "$NODE_PID" > "$PIDFILE"

ready=0
i=0
while [ "$i" -lt 50 ]; do
  if page_up; then
    ready=1
    break
  fi
  i=$((i + 1))
  sleep 0.2
done

if [ "$ready" -ne 1 ]; then
  echo "KeyBridge Platform did not open. Run sh KeyBridgePlatform again."
  kill "$NODE_PID" 2>/dev/null || true
  exit 1
fi

open_browser
echo "KeyBridge Platform is open. You can close this terminal."
