#!/usr/bin/env bash
set -euo pipefail

PACK_NAME="Dimensional Doors Recovery 1.4.7"
HOSTNAME="dimdoors.system42.one"
BRIDGE="127.0.0.1:25570"
STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/dimdoors-recovery"
PID_FILE="$STATE_DIR/cloudflared.pid"
LOG_FILE="$STATE_DIR/cloudflared.log"

find_launcher() {
  for command_name in prismlauncher PrismLauncher multimc MultiMC; do
    if command -v "$command_name" >/dev/null 2>&1; then
      command -v "$command_name"
      return
    fi
  done
  if [[ -x /opt/multimc/run.sh ]]; then
    echo /opt/multimc/run.sh
    return
  fi
  if [[ -x "$HOME/.local/bin/PrismLauncher.AppImage" ]]; then
    echo "$HOME/.local/bin/PrismLauncher.AppImage"
    return
  fi
  return 1
}

install_cloudflared() {
  if command -v cloudflared >/dev/null 2>&1; then
    command -v cloudflared
    return
  fi
  mkdir -p "$HOME/.local/bin"
  local arch url target
  arch="$(uname -m)"
  case "$arch" in
    aarch64|arm64) url="https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm64" ;;
    x86_64|amd64) url="https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64" ;;
    *) echo "Unsupported cloudflared architecture: $arch" >&2; exit 1 ;;
  esac
  target="$HOME/.local/bin/cloudflared"
  curl -fL "$url" -o "$target"
  chmod +x "$target"
  echo "$target"
}

mkdir -p "$STATE_DIR"
CLOUDFLARED="$(install_cloudflared)"
if [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
  echo "Cloudflare bridge is already running."
else
  nohup "$CLOUDFLARED" access tcp --hostname "$HOSTNAME" --url "$BRIDGE" --logfile "$LOG_FILE" --log-level info >/dev/null 2>&1 &
  echo $! > "$PID_FILE"
  sleep 2
fi

LAUNCHER="$(find_launcher || true)"
if [[ -z "$LAUNCHER" ]]; then
  echo "Prism Launcher or MultiMC is not installed. Run install-and-launch-linux.sh first." >&2
  exit 1
fi
DATA_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")"
nohup "$LAUNCHER" -d "$DATA_ROOT" -l "$PACK_NAME" -s "$BRIDGE" >/dev/null 2>&1 &
echo "Started $PACK_NAME through $HOSTNAME on $BRIDGE"
