#!/usr/bin/env bash

# Script Version
VER=6
VER_FILE="/etc/bazzite/flatpak_manager_version"
VER_RAN=$(cat $VER_FILE)

# Run script if updated
if [[ -f $VER_FILE && $VER = $VER_RAN ]]; then
  echo "Flatpak manager v$VER has already ran. Exiting..."
  exit 0
fi

# Opt out of and remove Fedora's flatpak repo
if grep -qz 'fedora' <<< $(flatpak remotes); then
  /usr/lib/fedora-third-party/fedora-third-party-opt-out
  /usr/bin/fedora-third-party disable
  flatpak remote-delete fedora --force
fi

# Ensure Flathub is enabled
flatpak remote-modify --system --enable flathub

# Lists of flatpaks
FLATPAK_LIST=$(flatpak list --columns=application)
INSTALL_LIST=$(cat /usr/share/ublue-os/bazzite/flatpak/install)
REMOVE_LIST=$(cat /usr/share/ublue-os/bazzite/flatpak/remove)

# Install flatpaks in list
if [[ -n $INSTALL_LIST ]]; then
  if ! flatpak install --system --noninteractive flathub ${INSTALL_LIST[@]}; then
    # exit on error
    exit 1
  fi
fi

# Remove flatpaks in list
if [[ -n $REMOVE_LIST ]]; then
  flatpak remove --system --noninteractive ${REMOVE_LIST[@]}
fi

mkdir -p /etc/bazzite
echo $VER > $VER_FILE
