#!/bin/bash
# Privileged helper for edubuntu-menu-admin (called via pkexec).

OVERRIDE_DIR="/usr/share/edubuntu/applications"
CONTENT="[Desktop Entry]\nNoDisplay=true\n"

apply_global() {
    # Clear existing overrides
    for f in "$OVERRIDE_DIR"/*.desktop; do
        [ -f "$f" ] && rm -f "$f"
    done
    # Write new overrides
    for name in "$@"; do
        printf "$CONTENT" > "$OVERRIDE_DIR/$name"
    done
}

apply_user() {
    local username="$1"
    shift

    # Validate user exists
    if ! id "$username" >/dev/null 2>&1; then
        echo "Unknown user: $username" >&2
        exit 1
    fi

    local homedir
    homedir=$(eval echo "~$username")
    local user_apps="$homedir/.local/share/applications"

    # Ensure directory exists with correct ownership
    if [ ! -d "$user_apps" ]; then
        install -d -o "$username" -g "$(id -gn "$username")" "$user_apps"
    fi

    # Clear existing edubuntu overrides (only NoDisplay=true stubs we wrote)
    for f in "$user_apps"/*.desktop; do
        [ -f "$f" ] || continue
        if grep -qx 'NoDisplay=true' "$f" 2>/dev/null; then
            # Only remove if it's our 2-3 line stub, not a real user override
            lines=$(wc -l < "$f")
            if [ "$lines" -le 3 ]; then
                chattr -i "$f" 2>/dev/null
                rm -f "$f"
            fi
        fi
    done

    # Write new overrides owned by root and marked immutable so the
    # user cannot remove or edit them.
    for name in "$@"; do
        printf "$CONTENT" > "$user_apps/$name"
        chmod 644 "$user_apps/$name"
        chattr +i "$user_apps/$name"
    done
}

case "$1" in
    global)
        shift
        apply_global "$@"
        ;;
    user)
        shift
        apply_user "$@"
        ;;
    *)
        echo "Usage: $0 {global|user <username>} [file.desktop ...]" >&2
        exit 1
        ;;
esac
