#!/usr/bin/env bash
# ansipa-install-flatpaks.sh — install Flatpak apps based on FreeIPA group membership.
#
# IPA group naming convention (dots encoded as double underscores):
#   dev_fp_org__mozilla__firefox   → installs org.mozilla.firefox
#   dev_fp_com__spotify__Client    → installs com.spotify.Client
#   dev_fp_io__missioncenter__MissionCenter → installs io.missioncenter.MissionCenter
#
# Decoding: strip "dev_fp_" prefix, then replace every __ with a dot.
# Single underscores in Flatpak IDs are preserved as-is.
#
# Scope: system-wide (--system), runs as root via systemd service.

set -e

PREFIX="dev_fp_"

# ── Preflight ─────────────────────────────────────────────────────────────────
if ! command -v flatpak &>/dev/null; then
    echo "[ansipa-flatpaks] flatpak not installed — nothing to do."
    exit 0
fi

if ! command -v ipa &>/dev/null; then
    echo "[ansipa-flatpaks] ipa command not found — host not enrolled in FreeIPA."
    exit 0
fi

kinit -k "host/$(hostname -f)" &>/dev/null || true

# ── Ensure Flathub remote is configured (system scope) ───────────────────────
if ! flatpak remote-list --system | awk '{print $1}' | grep -qx "flathub"; then
    echo "[ansipa-flatpaks] Adding Flathub system remote..."
    flatpak remote-add --system --if-not-exists flathub \
        https://dl.flathub.org/repo/flathub.flatpakrepo
fi

# ── Discover IPA groups matching dev_fp_* ────────────────────────────────────
# ipa group-find --pkey-only outputs one group name per line (possibly indented).
# $NF captures the name regardless of leading label text.
IPA_GROUPS=$(ipa group-find --pkey-only 2>/dev/null \
    | awk '{print $NF}' \
    | grep "^${PREFIX}" \
    || true)

if [[ -z "$IPA_GROUPS" ]]; then
    echo "[ansipa-flatpaks] No ${PREFIX}* groups found in IPA — nothing to install."
    exit 0
fi

# ── Decode group names → Flatpak application IDs ─────────────────────────────
# 1. Strip the dev_fp_ prefix
# 2. Replace every __ with a literal dot
DESIRED_FLATPAKS=()
while IFS= read -r G; do
    [[ -z "$G" ]] && continue
    FLATPAK_ID=$(echo "$G" \
        | sed "s/^${PREFIX}//" \
        | sed 's/__/./g')

    # Validate: must be reverse-domain notation with at least two components
    if ! echo "$FLATPAK_ID" | grep -qE '^[a-zA-Z][a-zA-Z0-9_-]*(\.[a-zA-Z0-9][a-zA-Z0-9_-]*)+$'; then
        echo "[ansipa-flatpaks][WARN] '$FLATPAK_ID' (from group '$G') is not a valid Flatpak ID — skipping."
        continue
    fi

    DESIRED_FLATPAKS+=("$FLATPAK_ID")
done <<< "$IPA_GROUPS"

if [[ ${#DESIRED_FLATPAKS[@]} -eq 0 ]]; then
    echo "[ansipa-flatpaks] No valid Flatpak IDs decoded from IPA groups."
    exit 0
fi

echo "[ansipa-flatpaks] Desired Flatpaks: ${DESIRED_FLATPAKS[*]}"

# ── Get currently installed system Flatpaks ───────────────────────────────────
INSTALLED=$(flatpak list --system --app --columns=application 2>/dev/null || true)

# ── Install missing apps ──────────────────────────────────────────────────────
for ID in "${DESIRED_FLATPAKS[@]}"; do
    if echo "$INSTALLED" | grep -qx "$ID"; then
        echo "[ansipa-flatpaks] Already installed: $ID"
    else
        echo "[ansipa-flatpaks] Installing: $ID"
        flatpak install --system -y --noninteractive flathub "$ID" \
            && echo "[ansipa-flatpaks] Installed: $ID" \
            || echo "[ansipa-flatpaks][WARN] Failed to install: $ID"
    fi
done
