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

PACK_NAME="Dimensional Doors Recovery 1.4.7"
API="https://api.github.com/repos/PrismLauncher/PrismLauncher/releases/latest"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

instance_dir() {
  if command -v flatpak >/dev/null 2>&1 && flatpak info org.prismlauncher.PrismLauncher >/dev/null 2>&1; then
    echo "$HOME/.var/app/org.prismlauncher.PrismLauncher/data/PrismLauncher/instances"
  elif [[ -d "$HOME/.local/share/PrismLauncher" ]]; then
    echo "$HOME/.local/share/PrismLauncher/instances"
  elif [[ -d "$HOME/.local/share/multimc" ]]; then
    echo "$HOME/.local/share/multimc/instances"
  else
    echo "$HOME/.local/share/PrismLauncher/instances"
  fi
}

if [[ ! -d "$SCRIPT_DIR/.minecraft" || ! -f "$SCRIPT_DIR/mmc-pack.json" ]]; then
  echo "Run this script from inside the extracted '$PACK_NAME' folder." >&2
  exit 1
fi

TARGET="$(instance_dir)/$PACK_NAME"
mkdir -p "$TARGET"
if [[ "$(readlink -f "$SCRIPT_DIR")" != "$(readlink -f "$TARGET" 2>/dev/null || true)" ]]; then
  if command -v rsync >/dev/null 2>&1; then
    rsync -a --delete --exclude '.minecraft/logs/' --exclude '.minecraft/screenshots/' --exclude '.minecraft/saves/' "$SCRIPT_DIR/" "$TARGET/"
  else
    cp -a "$SCRIPT_DIR/." "$TARGET/"
  fi
fi
chmod +x "$TARGET/connect-linux.sh" "$TARGET/install-and-launch-linux.sh"

if ! command -v prismlauncher >/dev/null 2>&1 && ! command -v multimc >/dev/null 2>&1 && [[ ! -x "$HOME/.local/bin/PrismLauncher.AppImage" ]]; then
  mkdir -p "$HOME/.local/bin"
  arch="$(uname -m)"
  if [[ "$arch" == "aarch64" || "$arch" == "arm64" ]]; then
    asset="PrismLauncher-Linux-aarch64.AppImage"
  else
    asset="PrismLauncher-Linux-x86_64.AppImage"
  fi
  url="$(curl -fsSL "$API" | grep -Eo '"browser_download_url": "[^"]+'"$asset"'"' | head -n1 | cut -d '"' -f4)"
  curl -fL "$url" -o "$HOME/.local/bin/PrismLauncher.AppImage"
  chmod +x "$HOME/.local/bin/PrismLauncher.AppImage"
fi

mkdir -p "$HOME/.local/share/applications"
cat > "$HOME/.local/share/applications/dimdoors-recovery.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=Dimensional Doors Recovery 1.4.7
Comment=Connect through Cloudflare and launch the independent recovery client
Exec=bash "$TARGET/connect-linux.sh"
Terminal=true
Categories=Game;
EOF
chmod +x "$HOME/.local/share/applications/dimdoors-recovery.desktop"

exec "$TARGET/connect-linux.sh"
