#!/bin/sh
set -e
# Adds or removes FileBench in the system list of default programs; every other line stays as it is.
LIST="${FILEBENCH_LIST:-/etc/xdg/mimeapps.list}"
ID=au.kalretro.FileBench.desktop
fb_off() {
    [ -f "$LIST" ] && grep -q "$ID" "$LIST" || return 0
    t=$(mktemp "$LIST.XXXXXX")
    awk -v id="$ID" '/^inode\/directory=/ { n = split(substr($0, 17), a, ";"); s = ""; for (i = 1; i <= n; i++) if (a[i] != "" && a[i] != id) s = s a[i] ";"; if (s == "") next; print "inode/directory=" s; next } { print }' "$LIST" > "$t"
    chmod 644 "$t"
    if [ "$(grep -v '^$' "$t")" = "[Default Applications]" ]; then rm -f "$t" "$LIST"; else mv "$t" "$LIST"; fi
}
fb_on() {
    fb_off
    mkdir -p "$(dirname "$LIST")"
    [ -f "$LIST" ] || printf '[Default Applications]\n' > "$LIST"
    grep -q '^\[Default Applications\]' "$LIST" || printf '\n[Default Applications]\n' >> "$LIST"
    t=$(mktemp "$LIST.XXXXXX")
    awk -v id="$ID" 'function add() { if (in_ && !done) { print "inode/directory=" id ";"; done = 1 } }
        /^\[/ { add(); in_ = ($0 ~ /^\[Default Applications\]/) ; print; next }
        in_ && !done && /^inode\/directory=/ { print "inode/directory=" id ";" substr($0, 17); done = 1; next }
        in_ && !done && /^$/ { add() }
        { print } END { add() }' "$LIST" > "$t"
    chmod 644 "$t"
    mv "$t" "$LIST"
}
# Makes FileBench the Open/Save window for every user (the FileChooser line of the desktop portal's settings), or takes it away again.
# The portal reads only the first settings file it finds for a desktop, so a new one in /etc/xdg starts as a copy of the system one.
PDIR="${FILEBENCH_PORTAL_DIR:-/etc/xdg/xdg-desktop-portal}"
PSYS="${FILEBENCH_PORTAL_SYS:-/usr/share/xdg-desktop-portal}"
PKEY=org.freedesktop.impl.portal.FileChooser
PMARK="# Written by the FileBench package; removed with it."
PADD="# The next line was added by the FileBench package."
fbp_pref() { # value of a key in [preferred], or nothing
    awk -v k="$2" '/^[ \t]*\[/ { in_ = ($0 ~ /^[ \t]*\[preferred\][ \t]*$/); next } in_ { l = $0; sub(/^[ \t]+/, "", l); n = index(l, "="); if (n) { key = substr(l, 1, n - 1); sub(/[ \t]+$/, "", key); if (key == k) { v = substr(l, n + 1); gsub(/^[ \t]+|[ \t]+$/, "", v); print v; exit } } }' "$1"
}
fbp_strip() { # a portal list without filebench
    printf '%s' "$1" | awk -F';' '{ s = ""; for (i = 1; i <= NF; i++) { x = $i; gsub(/^[ \t]+|[ \t]+$/, "", x); if (x != "" && x != "filebench") s = s x ";" } sub(/;$/, "", s); print s }'
}
fbp_set() { # file, new value (empty: the line goes), comment line or nothing: puts key=value in [preferred], replacing the key's line
    t=$(mktemp "$1.XXXXXX")
    awk -v k="$PKEY" -v v="$2" -v c="$3" 'function put() { if (!done) { if (v != "") { if (c != "") print c; print k "=" v }; done = 1 } }
        function blanks() { for (; b > 0; b--) print "" }
        /^[ \t]*\[/ { if (in_) put(); blanks(); in_ = ($0 ~ /^[ \t]*\[preferred\][ \t]*$/); had = had || in_; print; next }
        in_ && /^[ \t]*$/ { b++; next }
        in_ { blanks(); l = $0; sub(/^[ \t]+/, "", l); n = index(l, "="); if (n) { key = substr(l, 1, n - 1); sub(/[ \t]+$/, "", key); if (key == k) { put(); next } } }
        { print } END { if (!had) print "[preferred]"; if (in_ || !had) put(); blanks() }' "$1" > "$t"
    chmod 644 "$t"; mv "$t" "$1"
}
fbp_files() { # the desktops that have system settings
    for s in "$PSYS"/*portals.conf; do [ -f "$s" ] && basename "$s"; done
}
fb_portal_on() {
    mkdir -p "$PDIR"
    for n in $(fbp_files); do
        f="$PDIR/$n"
        if [ ! -f "$f" ]; then { echo "$PMARK"; cat "$PSYS/$n"; } > "$f"; chmod 644 "$f"; fi
        old=$(fbp_pref "$f" "$PKEY")
        if grep -qxF "$PADD" "$f" || grep -qxF "$PMARK" "$f" || [ -n "$old" ]; then c=""; else c="$PADD"; fi
        rest=$(fbp_strip "$old"); [ -n "$rest" ] || rest=$(fbp_strip "$(fbp_pref "$f" default)")
        fbp_set "$f" "filebench${rest:+;$rest}" "$c"
    done
}
fb_portal_off() {
    for f in "$PDIR"/*portals.conf; do
        [ -f "$f" ] || continue
        if grep -qxF "$PMARK" "$f"; then rm -f "$f"; continue; fi
        old=$(fbp_pref "$f" "$PKEY")
        case ";$old;" in *";filebench;"*) ;; *) continue ;; esac
        if grep -qxF "$PADD" "$f"; then
            t=$(mktemp "$f.XXXXXX")
            awk -v a="$PADD" -v k="$PKEY" '$0 == a { skip = 1; next } skip { skip = 0; l = $0; sub(/^[ \t]+/, "", l); if (index(l, k "=") == 1) next } { print }' "$f" > "$t"
            chmod 644 "$t"; mv "$t" "$f"
        else
            fbp_set "$f" "$(fbp_strip "$old")" ""
        fi
    done
    rmdir "$PDIR" 2>/dev/null || true
}
case "$1" in remove|purge) fb_off; fb_portal_off ;; esac
if [ "$1" = purge ] && [ -e /usr/share/debconf/confmodule ]; then
    . /usr/share/debconf/confmodule
    db_purge
fi
exit 0
