#!/bin/bash

# Hash triggers (Script runs if these files change):
# dnf: {{ include "apps-dnf.txt" | sha256sum }}
# flatpak: {{ include "apps-flatpak.txt" | sha256sum }}
# vscode: {{ include "vscode-extensions.txt" | sha256sum }}

echo "🚀 Change detected in Fedora app lists. Restoring environment..."

# 1. Install DNF Packages
# We use .chezmoi.sourceDir to find the file during the apply process
if [ -f "{{ .chezmoi.sourceDir }}/apps-dnf.txt" ]; then
    echo "Installing DNF packages..."
    # Using xargs is safer for large lists
    sudo dnf install -y $(cat "{{ .chezmoi.sourceDir }}/apps-dnf.txt")
fi

# 2. Install Flatpaks
if [ -f "{{ .chezmoi.sourceDir }}/apps-flatpak.txt" ]; then
    echo "Installing Flatpaks..."
    while read -r fp; do
        # Basic check to skip empty lines
        [[ -z "$fp" ]] && continue
        flatpak install -y flathub "$fp"
    done < "{{ .chezmoi.sourceDir }}/apps-flatpak.txt"
fi

# 3. Restore VS Code Extensions
if command -v code &> /dev/null; then
    if [ -f "{{ .chezmoi.sourceDir }}/vscode-extensions.txt" ]; then
        echo "Restoring VS Code Extensions..."
        while read -r extension; do
            [[ -z "$extension" ]] && continue
            code --install-extension "$extension" --force
        done < "{{ .chezmoi.sourceDir }}/vscode-extensions.txt"
    fi
fi

echo "✅ Fedora environment is up to date!"
