#!/bin/sh
# One-time migration: adopt Videos (rikkiti-videos) as the default for videos, and for a sound file opened on its own.
#
# Runs at login (from rikkiti-session), guarded by a marker file so it takes effect EXACTLY ONCE per user: the first
# login after Videos ships. Homes made before it have mpv 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 mpv or from nothing:
# anyone who chose another player (VLC, Celluloid) keeps it. On every later login the marker is there and this does
# nothing. Music stays a right-click away (Open With): opened in Music, a file would take the place of Up Next.
set -eu
marker="${XDG_CONFIG_HOME:-$HOME/.config}/rikkiti/.videos-is-default"
[ -e "$marker" ] && exit 0
command -v rikkiti-videos >/dev/null 2>&1 || exit 0
mkdir -p "$(dirname "$marker")"
list="${XDG_CONFIG_HOME:-$HOME/.config}/mimeapps.list"
for t in video/mp4 video/x-matroska video/webm video/quicktime video/x-msvideo video/mpeg video/ogg video/x-ms-wmv \
         video/x-flv video/3gpp video/mp2t video/x-m4v audio/mpeg audio/flac audio/x-flac audio/ogg audio/x-vorbis+ogg \
         audio/opus audio/x-wav audio/mp4 audio/x-m4a audio/aac; 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
		"" | mpv.desktop | io.mpv.Mpv.desktop) xdg-mime default rikkiti-videos.desktop "$t" 2>/dev/null || true ;;
	esac
done
: > "$marker"
