#!/usr/bin/env bash
# Keeps the machine's Flatpak apps in sync with /usr/share/kamos/flatpaks.list.
# Runs on every boot but does nothing unless the list changed since last time,
# so adding an app to the list + rebuilding the image is enough — installed
# machines pick it up on their next update, no reinstall needed.
set -u

LIST=/usr/share/kamos/flatpaks.list
STATE=/var/lib/kamos-flatpaks.sha

[ -f "$LIST" ] || exit 0

NEW="$(sha256sum "$LIST" | awk '{print $1}')"
OLD="$(cat "$STATE" 2>/dev/null || true)"
[ "$NEW" = "$OLD" ] && exit 0

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

ok=1
while IFS= read -r app; do
    case "$app" in ''|\#*) continue ;; esac
    app="${app%%#*}"; app="$(echo "$app" | xargs)"
    [ -z "$app" ] && continue
    echo "KAMOS: installing $app"
    flatpak install --system --noninteractive --or-update flathub "$app" || ok=0
done < "$LIST"

# Only record success, so a failed run (e.g. no network yet) retries next boot
[ "$ok" = 1 ] && echo "$NEW" > "$STATE"
exit 0
