#!/bin/bash

# fatdog-sync-mime-update-desktop-database.sh - Copyright (C) step 2022
# License: GNU GPL Version 3 or later

# ------------------------------------------------------------------------------
# Editing this file: please set your tabstop = 8 and indent lines with TABS.
# Read purpose, compatibility and notes at the end of fatdog-sync-mime-lib.sh.
# ------------------------------------------------------------------------------

usage () {
	cat << EOF
Usage: [Environment] ${0##*/} [\$1-ROOT]
ROOT             work tree, default '/'

Environment:
NO_BUILD_CACHE=1 do not run update-desktop-database(1) before other steps
SYSTEM_ONLY=1    limit work to system directories (\$1-ROOT applies)
USER_ONLY=1      limit work to user's home (\$1-ROOT applies)
EOF
}

case "$1" in '-h'|'--help') usage; exit ;; esac

source "${0%update-desktop-database.sh}lib.sh" || exit $?

################################################################################
#                                     MAIN                                     #
################################################################################

PS4='+ $FUNCNAME:$LINENO: '
set_vars "$1"
#trap "rm -f '${TMP:?}-'*" EXIT

((is_root=!UID))

### update all mimeinfo.cache files and merge in mimeapps.list files

if ((is_root && ! USER_ONLY)); then
	for (( i = 0; i < ${#DATA_DIRS[*]}; i++ )); do
		if [ -d "${DATA_DIRS[$i]}/applications" ]; then
		(
			${NO_BUILD_CACHE:+":"} update-desktop-database \
				"${DATA_DIRS[$i]}/applications" \
			&& rearrange_mimeinfo_cache \
				"${DATA_DIRS[$i]}/applications/mimeinfo.cache" \
				"${DATA_DIRS[$i]}/applications/mimeapps.list"
		) &
		fi
	done
fi

if ((! SYSTEM_ONLY)) && [ -d "$LOCAL_DESKTOP_FILE_DIR" ]; then
	(
		${NO_BUILD_CACHE:+":"} update-desktop-database \
			"$LOCAL_DESKTOP_FILE_DIR" \
		&& rearrange_mimeinfo_cache \
			"$LOCAL_DESKTOP_FILE_DIR/mimeinfo.cache" \
			"$LOCAL_MIMEAPPS_LIST"
	) &
fi

wait

# not tracking script status
exit

