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

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

TERMINAL_SENTINEL="__disable_terminal_shortcut__"
DCONF_SITE_DIR="/etc/dconf/db/site.d"
DCONF_LOCKS_DIR="${DCONF_SITE_DIR}/locks"
DCONF_TERMINAL_FILE="${DCONF_SITE_DIR}/02_edubuntu_terminal"
DCONF_TERMINAL_LOCK="${DCONF_LOCKS_DIR}/edubuntu-terminal"
TERMINAL_DCONF_KEY="/org/gnome/settings-daemon/plugins/media-keys/terminal"

# ── Terminal shortcut helpers ──────────────────────────────────────

apply_terminal_global() {
    local disable="$1"
    if [ "$disable" = "true" ]; then
        mkdir -p "$DCONF_SITE_DIR" "$DCONF_LOCKS_DIR"
        cat > "$DCONF_TERMINAL_FILE" <<EOF
[org/gnome/settings-daemon/plugins/media-keys]
terminal=''
EOF
        echo "$TERMINAL_DCONF_KEY" > "$DCONF_TERMINAL_LOCK"
    else
        rm -f "$DCONF_TERMINAL_FILE" "$DCONF_TERMINAL_LOCK"
    fi
    if command -v dconf >/dev/null 2>&1; then
        dconf update
    fi
}

write_user_dconf() {
    local username="$1"
    local key="$2"
    local value="$3"
    local uid
    uid=$(id -u "$username")

    if [ -S "/run/user/${uid}/bus" ]; then
        sudo -u "$username" \
            DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${uid}/bus" \
            dconf write "$key" "$value" 2>/dev/null && return 0
    fi
    sudo -u "$username" dbus-run-session \
        dconf write "$key" "$value" 2>/dev/null || true
}

reset_user_dconf() {
    local username="$1"
    local key="$2"
    local uid
    uid=$(id -u "$username")

    if [ -S "/run/user/${uid}/bus" ]; then
        sudo -u "$username" \
            DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${uid}/bus" \
            dconf reset "$key" 2>/dev/null && return 0
    fi
    sudo -u "$username" dbus-run-session \
        dconf reset "$key" 2>/dev/null || true
}

apply_terminal_user() {
    local username="$1"
    local disable="$2"
    local homedir
    homedir=$(eval echo "~$username")
    local marker_dir="${homedir}/.config/edubuntu"
    local marker="${marker_dir}/terminal-disabled"

    if [ "$disable" = "true" ]; then
        write_user_dconf "$username" "$TERMINAL_DCONF_KEY" "''"
        mkdir -p "$marker_dir"
        touch "$marker"
        chown -R "${username}:$(id -gn "$username")" "$marker_dir"
    else
        reset_user_dconf "$username" "$TERMINAL_DCONF_KEY"
        rm -f "$marker"
    fi
}

# ── App override helpers ───────────────────────────────────────────

apply_global() {
    local terminal_disable=false
    local desktop_files=()

    for name in "$@"; do
        if [ "$name" = "$TERMINAL_SENTINEL" ]; then
            terminal_disable=true
        else
            desktop_files+=("$name")
        fi
    done

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

    # Handle terminal shortcut
    apply_terminal_global "$terminal_disable"
}

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

    # Separate terminal sentinel from desktop files
    local terminal_disable=false
    local desktop_files=()

    for name in "$@"; do
        if [ "$name" = "$TERMINAL_SENTINEL" ]; then
            terminal_disable=true
        else
            desktop_files+=("$name")
        fi
    done

    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 "${desktop_files[@]}"; do
        printf "$CONTENT" > "$user_apps/$name"
        chmod 644 "$user_apps/$name"
        chattr +i "$user_apps/$name"
    done

    # Handle terminal shortcut
    apply_terminal_user "$username" "$terminal_disable"
}

query_user() {
    # For each username, output "username<TAB>filename" for every .desktop
    # file in their ~/.local/share/applications/ that contains NoDisplay=true.
    # Also outputs the terminal sentinel if terminal is disabled for the user.
    for username in "$@"; do
        if ! id "$username" >/dev/null 2>&1; then
            continue
        fi
        local homedir
        homedir=$(eval echo "~$username")
        local user_apps="$homedir/.local/share/applications"
        if [ -d "$user_apps" ]; then
            for f in "$user_apps"/*.desktop; do
                [ -f "$f" ] || continue
                if grep -qx 'NoDisplay=true' "$f" 2>/dev/null; then
                    printf '%s\t%s\n' "$username" "$(basename "$f")"
                fi
            done
        fi
        # Check terminal shortcut marker (independent of user_apps)
        if [ -f "$homedir/.config/edubuntu/terminal-disabled" ]; then
            printf '%s\t%s\n' "$username" "$TERMINAL_SENTINEL"
        fi
    done
}

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