#!/bin/sh
# One-time migration: archives (zip, tar, 7z, rar…) open in Files, which looks inside them itself now, rather than in
# File Roller.
#
# Runs at login (from rikkiti-session), guarded by a marker file so it takes effect EXACTLY ONCE per user: the first
# login after Files does archives. Homes made before it have File Roller as the default in their own mimeapps.list (a
# copy of /etc/skel's), which beats the system default — so each type is changed here, but only from File Roller or
# from nothing: anyone who chose another archive app (Ark, Xarchiver) keeps it.
set -eu
marker="${XDG_CONFIG_HOME:-$HOME/.config}/rikkiti/.files-opens-archives"
[ -e "$marker" ] && exit 0
command -v rikkiti-files >/dev/null 2>&1 || exit 0
mkdir -p "$(dirname "$marker")"
list="${XDG_CONFIG_HOME:-$HOME/.config}/mimeapps.list"
for t in application/zip application/x-tar application/x-compressed-tar application/x-bzip-compressed-tar \
         application/x-xz-compressed-tar application/x-zstd-compressed-tar application/x-7z-compressed application/vnd.rar \
         application/x-rar application/gzip application/x-xz application/x-bzip2 application/zstd application/x-cpio \
         application/x-lzma application/x-lzip application/x-lz4 application/x-bzip1-compressed-tar \
         application/x-lz4-compressed-tar application/x-lzip-compressed-tar application/x-lzma-compressed-tar \
         application/x-tarz application/x-compress application/vnd.ms-cab-compressed application/x-lha application/x-xar; do
	# the user's own choice, from their own file (`xdg-mime query` answers from the system's layers past it)
	now="$(grep -F "$t=" "$list" 2>/dev/null | grep "^$t=" | head -1 | sed 's/^[^=]*=\([^;]*\).*/\1/')"
	case "$now" in
		"" | org.gnome.FileRoller.desktop | file-roller.desktop) xdg-mime default rikkiti-files.desktop "$t" 2>/dev/null || true ;;
	esac
done
: > "$marker"
