#!/bin/bash
#
# Copy the MX/antiX Plasma default overrides onto the files Plasma ships.
#
# This package deliberately does not install into /usr/share/plasma itself:
# three of these files are owned by plasma-workspace/plasma-desktop, and a
# package that ships a path another installed package owns makes every pacman
# transaction fail with "conflicting files" (see lib/alpm/conflict.c).  So the
# overrides live in /usr/share/mx-plasma-defaults and this script copies them
# onto the Plasma originals, driven by a pacman hook whenever either Plasma
# package is installed or upgraded.  The MX defaults therefore survive Plasma
# updates without two packages claiming one path.
#
# Targets Plasma does not ship (as of Plasma 6.7, the three
# plasmoids/*/contents/config/main.xml defaults) are created; those paths are
# owned by nobody, and the previous packaging installed them directly.
#
# Exits non-zero if any file could not be written.  That cannot break a system
# upgrade: AbortOnFail only applies to PreTransaction hooks, and libalpm just
# warns if it is set on a PostTransaction one (lib/alpm/hook.c:141).

set -u

OVERRIDE_DIR=${OVERRIDE_DIR:-/usr/share/mx-plasma-defaults}
SHARE_DIR=${SHARE_DIR:-/usr/share}

if [[ ! -d $OVERRIDE_DIR ]]; then
    printf 'mx-plasma-defaults-apply: %s is missing\n' "$OVERRIDE_DIR" >&2
    exit 1
fi

status=0
created=0
updated=0
unchanged=0

while IFS= read -r -d '' override; do
    target=$SHARE_DIR/${override#"$OVERRIDE_DIR"/}

    if [[ -f $target ]] && cmp -s "$override" "$target"; then
        unchanged=$(( unchanged + 1 ))
        continue
    fi

    existed=0
    [[ -e $target ]] && existed=1

    if install -Dm644 "$override" "$target"; then
        if (( existed )); then
            updated=$(( updated + 1 ))
        else
            created=$(( created + 1 ))
        fi
    else
        printf 'mx-plasma-defaults-apply: cannot write %s\n' "$target" >&2
        status=1
    fi
done < <(find "$OVERRIDE_DIR" -type f -print0)

printf 'mx-plasma-defaults-apply: %d updated, %d created, %d already current\n' \
    "$updated" "$created" "$unchanged"

exit "$status"
