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

ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
VIEWER_DIR="$ROOT_DIR/miniview"
OPENVT_DIR="$ROOT_DIR/vendor/open-vt"
GODOT_BIN="${GODOT_BIN:-/nix/store/q2apsqxsljrzy2xpq26z774r5c30lagr-godot-4.6.2-stable/bin/godot4}"

export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
export WAYLAND_DISPLAY="${WAYLAND_DISPLAY:-wayland-1}"

if [ ! -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ]; then
  echo "Wayland socket not found: $XDG_RUNTIME_DIR/$WAYLAND_DISPLAY"
  exit 1
fi

mkdir -p "$VIEWER_DIR/addons"
mkdir -p "$VIEWER_DIR/.godot"

rm -rf "$VIEWER_DIR/addons/gd_cubism"
cp -R "$OPENVT_DIR/thirdparty/gd_cubism/demo/addons/gd_cubism" "$VIEWER_DIR/addons/gd_cubism"

mkdir -p "$VIEWER_DIR/addons/gd_cubism/bin/linux/x86_64"
cp "$OPENVT_DIR/addons/gd_cubism/bin/linux/x86_64/libgd_cubism.linux.debug.x86_64.so" "$VIEWER_DIR/addons/gd_cubism/bin/linux/x86_64/"
cp "$OPENVT_DIR/addons/gd_cubism/bin/linux/x86_64/libLive2DCubismCore.so" "$VIEWER_DIR/addons/gd_cubism/bin/linux/x86_64/"

cat > "$VIEWER_DIR/.godot/extension_list.cfg" <<'EOF'
res://addons/gd_cubism/gd_cubism.gdextension
EOF

mkdir -p "$VIEWER_DIR/addons/gd_cubism/example/res/live2d/Haru"
rm -rf "$VIEWER_DIR/addons/gd_cubism/example/res/live2d/Haru"
cp -R /home/nandi/.local/share/godot/app_userdata/open-vt/Live2DModels/Haru "$VIEWER_DIR/addons/gd_cubism/example/res/live2d/Haru"

exec "$GODOT_BIN" --path "$VIEWER_DIR"
