#!/bin/bash
# Install the KDE Linux application set from Flathub once.
# The marker is written only after every listed application is installed,
# so the next boot retries a partial download.
# --missing only reports. The package upgrade uses it to clear the marker
# when the list has grown. It does not install anything.
set -eu

marker=/var/lib/atropos/flatpaks-seeded
list=/usr/share/atropos/flatpak-preinstall.txt
check_only=0
if [[ ${1-} == --missing ]]; then
    check_only=1
fi

mapfile -t apps < <(grep -vE '^[[:space:]]*(#|$)' "$list")
missing=()
for id in "${apps[@]}"; do
    if ! flatpak info --system "$id" >/dev/null 2>&1; then
        missing+=("$id")
    fi
done
if ((check_only)); then
    if ((${#missing[@]} > 0)); then
        exit 1
    fi
    exit 0
fi
if [[ -f $marker ]]; then
    exit 0
fi

if ! flatpak remotes --system --columns=name | grep -qx flathub; then
    flatpak remote-add --if-not-exists --system flathub \
        https://dl.flathub.org/repo/flathub.flatpakrepo
fi

if ((${#missing[@]} > 0)); then
    flatpak install -y --noninteractive --system flathub "${missing[@]}"
fi
for id in "${apps[@]}"; do
    flatpak info --system "$id" >/dev/null 2>&1
done

install -d -m 0755 /var/lib/atropos
touch "$marker"
