#!/bin/sh
# One-time migration: adopt Documents (rikkiti-documents) as the default for PDFs.
#
# Runs at login (from rikkiti-session), guarded by a marker file so it takes effect EXACTLY ONCE per user: the first
# login after Documents ships. Homes made before it have Evince as the PDF default in their own mimeapps.list (a copy
# of /etc/skel's), which beats the system default — so it's changed here, but only from Evince or from nothing: anyone
# who chose another viewer keeps it. On every later login the marker is there and this does nothing.
set -eu
marker="${XDG_CONFIG_HOME:-$HOME/.config}/rikkiti/.documents-is-default"
[ -e "$marker" ] && exit 0
command -v rikkiti-documents >/dev/null 2>&1 || exit 0
mkdir -p "$(dirname "$marker")"

# the user's own choice, from their own file (`xdg-mime query` answers from the system's layers past it)
now="$(sed -n 's/^application\/pdf=\([^;]*\).*/\1/p' "${XDG_CONFIG_HOME:-$HOME/.config}/mimeapps.list" 2>/dev/null | head -1)"
case "$now" in
	"" | org.gnome.Evince.desktop | evince.desktop)
		xdg-mime default rikkiti-documents.desktop application/pdf application/x-pdf 2>/dev/null || true ;;
esac

: > "$marker"
