#!/usr/bin/env bash
# Per-user installation of the publisher's AppImage. Research/activation live outside this directory.
set -euo pipefail
if [[ $# -lt 1 || $# -gt 2 ]]; then
  echo 'Usage: bash install_ubuntu.sh /absolute/QRStudio.AppImage [absolute-prefix] OR --uninstall [absolute-prefix]' >&2
  exit 2
fi
prefix=${2:-"$HOME/.local"}
[[ "$prefix" = /* ]] || { echo 'Use an absolute prefix.' >&2; exit 2; }
prefix=$(realpath -m -- "$prefix")
[[ "$prefix" != / && "$prefix" != "$HOME" ]] || { echo 'Choose a dedicated installation prefix.' >&2; exit 2; }
app="$prefix/share/quantresearcher-studio"
launcher="$prefix/bin/qr-studio"
if [[ "$1" = --uninstall ]]; then
  [[ -f "$app/.qr-install" && ! -L "$app" && ! -L "$launcher" ]] || { echo 'No owned installation found.' >&2; exit 1; }
  [[ "$(cat "$app/.qr-install")" = 'QuantResearcher.Studio user install v1' ]] || exit 1
  # Remove only installer-owned files, never workspace data, journals or activation.
  if [[ -f "$launcher" ]] && grep -Fq '# QuantResearcher.Studio managed launcher v1' "$launcher"; then rm -- "$launcher"; fi
  rm -f -- "$app/QRStudio.AppImage" "$app/.qr-install"
  rmdir -- "$app" 2>/dev/null || true
  echo 'Application removed. Research workspace and PC activation are retained. Deactivate before uninstalling if transferring.'
  exit 0
fi
image=$(realpath -- "$1")
[[ -f "$image" && ! -L "$app" && ! -e "$app/QRStudio.AppImage" && ! -e "$launcher" ]] || { echo 'Use update install for an existing installation; no files were replaced.' >&2; exit 1; }
mkdir -p -- "$app" "$prefix/bin"
temporary=$(mktemp "$app/.install-XXXXXXXX")
trap 'rm -f -- "$temporary"' EXIT
cp -- "$image" "$temporary"
chmod 755 -- "$temporary"
mv -- "$temporary" "$app/QRStudio.AppImage"
printf '%s\n' 'QuantResearcher.Studio user install v1' > "$app/.qr-install"
# Resolve the image relative to this launcher; prefix never becomes executable shell source.
cat > "$launcher" <<'LAUNCHER'
#!/usr/bin/env bash
# QuantResearcher.Studio managed launcher v1
set -euo pipefail
base=$(cd -- "$(dirname -- "$0")/.." && pwd -P)
export APPIMAGE_EXTRACT_AND_RUN=1
exec "$base/share/quantresearcher-studio/QRStudio.AppImage" "$@"
LAUNCHER
chmod 755 -- "$launcher"
printf 'Installed: %s\nUse license activate, update check, or update install.\n' "$launcher"
