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

PACK_NAME="Dimensional Doors Recovery 1.4.7"
HOSTNAME="dimdoors.system42.one"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
TARGET="$HOME/Library/Application Support/PrismLauncher/instances/$PACK_NAME"
INSTALL_ROOT="$HOME/Applications/DimDoorsPrismLauncher"
API="https://api.github.com/repos/PrismLauncher/PrismLauncher/releases/latest"

mkdir -p "$TARGET"
if [[ "$SCRIPT_DIR" != "$TARGET" ]]; then
  rsync -a --delete --exclude '.minecraft/logs/' --exclude '.minecraft/screenshots/' --exclude '.minecraft/saves/' "$SCRIPT_DIR/" "$TARGET/"
fi

find_app() {
  for app in "/Applications/Prism Launcher.app" "/Applications/PrismLauncher.app" "$HOME/Applications/Prism Launcher.app" "$INSTALL_ROOT/PrismLauncher.app"; do
    [[ -d "$app" ]] && { echo "$app"; return; }
  done
}

APP="$(find_app || true)"
if [[ -z "$APP" ]]; then
  mkdir -p "$INSTALL_ROOT"
  url="$(curl -fsSL "$API" | grep -Eo '"browser_download_url": "[^"]+PrismLauncher-macOS-[^"]+\.zip"' | head -n1 | cut -d '"' -f4)"
  curl -fL "$url" -o "$INSTALL_ROOT/prismlauncher.zip"
  ditto -x -k "$INSTALL_ROOT/prismlauncher.zip" "$INSTALL_ROOT"
  APP="$(find_app || true)"
fi

mkdir -p "$HOME/.local/bin" "$HOME/Library/Logs/DimDoorsRecovery"
arch="$(uname -m)"
case "$arch" in
  arm64) cf_asset="cloudflared-darwin-arm64.tgz" ;;
  x86_64) cf_asset="cloudflared-darwin-amd64.tgz" ;;
  *) echo "Unsupported architecture: $arch" >&2; exit 1 ;;
esac
if [[ ! -x "$HOME/.local/bin/cloudflared" ]]; then
  curl -fL "https://github.com/cloudflare/cloudflared/releases/latest/download/$cf_asset" -o /tmp/dimdoors-cloudflared.tgz
  tar -xzf /tmp/dimdoors-cloudflared.tgz -C "$HOME/.local/bin" cloudflared
  chmod +x "$HOME/.local/bin/cloudflared"
fi
nohup "$HOME/.local/bin/cloudflared" access tcp --hostname "$HOSTNAME" --url 127.0.0.1:25570 --logfile "$HOME/Library/Logs/DimDoorsRecovery/cloudflared.log" --log-level info >/dev/null 2>&1 &
sleep 2
"$APP/Contents/MacOS/prismlauncher" -l "$PACK_NAME" -s 127.0.0.1:25570 >/dev/null 2>&1 &
echo "Started $PACK_NAME through $HOSTNAME"
