#!/bin/bash

# fatdog-sync-mime-core.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.
# ------------------------------------------------------------------------------

LANG=C # make it fly
# informal test i5-3210M @ 2.50GHz: 3.40 s vs 2.70 s (LANG=C) 2240 output rows

usage () {
	cat << EOF
Usage: [Environment] ${0##*/} [\$1-ROOT] [\$2-PLAN]
ROOT             work tree, default '/'
PLAN             work plan, default 'mimetypes+mailcap+mimeapps': cut as needed

Environment:
SYSTEM_ONLY=1    limit work to system directories (\$1-ROOT applies)
TABLE_OUT=path   output table (default none, use '-' for stdout)
USER_ONLY=1      limit work to user's home (\$1-ROOT applies)
WITH_AUDIT=1     get statistics and hints on stderr
EOF
}

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

p="${0%.sh}"; source "${p%-core}-lib.sh" || exit $?

# ---------------------------------------------------------------------------{{{
# Output: none
# ------------------------------------------------------------------------------
# [A] Fatdog only /etc/mailcap but potentially a globs2 file for each element
# of DATA_DIRS[]. Therefore we concatenate all globs2 found in DATA_DIRS and
# use it for /etc/mailcap, instead of just using DATA_DIRS[0]/mime/globs2.
# ---------------------------------------------------------------------------}}}
run_no_output_updates () {
	local -i i
	if ((is_root && ! USER_ONLY)); then
		for (( i = 0; i < ${#DATA_DIRS[*]}; i++ )); do
			[ -e "${DATA_DIRS["$i"]}/mime/globs2" ] &&
			set -- "$@" "${DATA_DIRS["$i"]}/mime/globs2"
		done
		update_mime_types "$MIMETYPES" <(cat "$@")
	fi

	if ((! SYSTEM_ONLY)); then
		update_mime_types "$LOCAL_MIMETYPES" "$LOCAL_GLOBS2"
	fi
}

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

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

find_best_realpath
((is_root=!UID))

#### begin process waiting wrapper ###
# see [bib9] and tbl8_update_mailcap_and_mimeapps_list [B]
{ {

# Main runs two tracks in parallel: updates that don't write to stdout
# (run_no_output_updates for mime.types), and updates that write the
# final data table to stdout (tbl8_update_mailcap_and_mimeapps_list).
# The latter forks sub-shells with >() process substitution.

run_no_output_updates &

### Run updates that output the final table

exec {table_out_fd}> "$TABLE_OUT" # /dev/null by default

>&${table_out_fd} tbl8_new_section 'system_begin'
if ((is_root && ! USER_ONLY)); then
	# about HARDCODED read note [A] of tbl8_rox_dir_table
	>&${table_out_fd} \
		HARDCODED='rox:inode_directory:/usr/bin/rox -d' \
		tbl8_update_mailcap_and_mimeapps_list '0' \
		"$ROX_HANDLER" \
		"$MAILCAP" \
		"${DATA_DIRS[0]}/applications"

	for (( i = 1; i < ${#DATA_DIRS[*]}; i++ )); do
		tbl8_desktop_dirs_table "$i" \
			"${DATA_DIRS["$i"]}/applications" |
			update_mimeapps_list \
				"${DATA_DIRS["$i"]}/applications/$MIMEAPPS_LIST" \
				>&${table_out_fd}
	done
fi
>&${table_out_fd} tbl8_new_section 'system_end'

>&${table_out_fd} tbl8_new_section 'user_begin'
if ((! SYSTEM_ONLY)); then
>&${table_out_fd} \
	HARDCODED='' \
	tbl8_update_mailcap_and_mimeapps_list "$i" \
	"$LOCAL_ROX_HANDLER" "$LOCAL_MAILCAP" \
	"$LOCAL_DESKTOP_FILE_DIR" \
	"$LOCAL_MIMEAPPS_LIST"
fi
>&${table_out_fd} tbl8_new_section 'user_end'

exec {table_out_fd}>&- # flush output table
((WITH_AUDIT)) && [[ "$TABLE_OUT" != '/dev/'* ]] && wc "$TABLE_OUT" >&2

#### end process waiting wrapper ####
} {fd3}>&1 1>&${fd4} {fd4}>&- | cat; } {fd4}>&1

# not tracking script status
exit

