#!/bin/sh
# Flathub remote + the two apps this image needs that Debian does not package:
# the official Spotify client and Prism Launcher.
#
# Same distribution channel and the same "don't pin a version that will just rot"
# reasoning as hosts/touch-panel's 0300-flatpak-spotify.hook.chroot and
# hosts/thin-client's 0400-flatpak-steamlink.hook.chroot.
#
# Note what is NOT here: Steam. Steam is installed natively from apt by
# 0300-steam.hook.chroot, deliberately — the Flatpak runs sandboxed with its own
# runtime, which complicates GPU driver matching, controller udev access and mounting
# a games disk, all of which matter on a machine whose whole job is running games
# locally. Prism and Spotify have none of those constraints, so the sandbox is a
# straightforward win for them.
set -eu

flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo

# VERIFY BEFORE THE FIRST REAL BUILD: confirm both application IDs against the live
# Flathub listing (`flatpak search Spotify`, `flatpak search "Prism Launcher"`).
# Believed correct — both are the publishers' own official listings — but not checked
# against Flathub from this environment.
SPOTIFY_APP_ID="com.spotify.Client"
PRISM_APP_ID="org.prismlauncher.PrismLauncher"

install_app() {
  app_id="$1"
  label="$2"
  if flatpak install -y --noninteractive flathub "$app_id"; then
    echo "0400-flatpak-apps: installed ${app_id}."
  else
    echo "0400-flatpak-apps: WARNING — could not install ${app_id} during the build (no"
    echo "  network in the chroot, or the app ID is wrong). Run this on the booted image"
    echo "  instead:  flatpak install -y flathub ${app_id}"
    echo "  Until then the ${label} launcher opens nothing."
  fi
}

install_app "$SPOTIFY_APP_ID" "Spotify"
install_app "$PRISM_APP_ID" "Prism Launcher"

# Prism needs a Java runtime it can actually see. The Flatpak's sandbox has its own
# filesystem view, so the openjdk packages in the package list are not visible inside
# it by default — this grants read access to the host's JVMs so Prism's auto-detection
# finds them and Minecraft launches with no network on first run.
if flatpak override --filesystem=/usr/lib/jvm:ro "$PRISM_APP_ID" 2>/dev/null; then
  echo "0400-flatpak-apps: granted Prism Launcher read access to /usr/lib/jvm."
else
  echo "0400-flatpak-apps: note — could not set the /usr/lib/jvm override (Prism is"
  echo "  probably not installed yet). Prism will download its own JRE on first launch,"
  echo "  which needs network at that moment. To fix it offline later:"
  echo "    flatpak override --user --filesystem=/usr/lib/jvm:ro ${PRISM_APP_ID}"
fi

# The games directory, so both Prism instances and any Steam library added later sit in
# one predictable place — see hosts/steam-tv-box/README.md on mounting a real disk there.
if flatpak override --filesystem=~/Games "$PRISM_APP_ID" 2>/dev/null; then
  echo "0400-flatpak-apps: granted Prism Launcher access to ~/Games."
fi
