#!/bin/sh
# Native Linux Hub; Wine is used only to read the selected Windows environment.
set -eu
base=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
config="${XDG_CONFIG_HOME:-$HOME/.config}/liminal-loud-hub-wine"
error() { if command -v zenity >/dev/null 2>&1; then zenity --error --title='Liminal Loud Hub' --text="$1"; else printf '%s\n' "$1" >&2; fi; exit 1; }
[ "$(uname -m)" = x86_64 ] || error 'This build requires Linux x86_64.'
command -v wine >/dev/null 2>&1 || error 'Wine is required. Use the same Wine installation as your Windows DAW.'
prefix=${WINEPREFIX:-}
if [ "${1:-}" = --prefix ]; then [ "$#" = 2 ] || error 'Usage: launch-hub --prefix /absolute/path/to/prefix'; prefix=$2
elif [ "$#" != 0 ]; then error 'Usage: launch-hub [--prefix /absolute/path/to/prefix]'
fi
if [ -z "$prefix" ] && [ -f "$config/prefix" ]; then IFS= read -r prefix < "$config/prefix" || :; fi
if [ -z "$prefix" ]; then
 if command -v zenity >/dev/null 2>&1; then prefix=$(zenity --file-selection --directory --title="Choose your DAW's Wine prefix (contains drive_c and system.reg)") || exit 0
 else error 'Choose your existing DAW prefix: ./launch-hub --prefix /absolute/path/to/prefix'; fi
fi
case "$prefix" in /*) ;; *) error 'The Wine prefix must be an absolute path.';; esac
[ -d "$prefix/drive_c" ] && [ -f "$prefix/system.reg" ] || error 'Choose the Wine prefix folder containing drive_c and system.reg.'
LC_ALL=C grep -qx '#arch=win64' "$prefix/system.reg" || error 'This build requires an existing 64-bit Wine prefix.'
prefix=$(CDPATH= cd -- "$prefix" && pwd -P)
# Keep each prefix's installed versions, queue and account state separate.
mkdir -p "$config" "$prefix/.liminal-loud-hub/config" "$prefix/.liminal-loud-hub/data"
printf '%s\n' "$prefix" > "$config/prefix"
export WINEPREFIX="$prefix"
exec "$base/hub" 2>"$prefix/.liminal-loud-hub/last-error.log"
