#!/bin/bash

# fatdog-sync-mime-make-desktop-files.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

usage () {
	cat << EOF
Usage: [Environment] ${0##*/} [\$1-ROOT] [\$2-PLAN] [\$3-SOURCE]
ROOT             work tree, default '/'
PLAN             work plan, default 'desktopfiles+mimeapps': cut as needed
                 or use 'dry-run' to only get the output table
SOURCE           sources, default 'MIME-types+SendTo+URI+mailcap': 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)
EOF
}

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

source "${0%make-desktop-files.sh}lib.sh" || exit $?

# out: $AWK
find_best_awk() {
	if type mawk > /dev/null; then
		AWK=mawk
	elif type gawk > /dev/null; then
		AWK=gawk
	elif type awk > /dev/null; then
		AWK=awk
	elif type busybox > /dev/null; then
		AWK="busybox awk"
	fi
}

# ---------------------------------------------------------------------------{{{
# This function reads fatdog-sync-mime-core's output TABLE@8 [A] on stdin.
# For each row that isn't associated to a .desktop file, it creates a new
# .desktop file in $1-extra_desktop_dir, and adds a new entry to file
# $2-extra_desktop_mimeapps_list via update_mimeapps_list - which overwrites an
# existing file.
# The resulting $extra_desktop_mimeapps.list file contains all the entries of
# the regular mimeapps.list file plus the entries corresponding to the new
# desktop files.  New desktop files names can be distinguished because they
# start with a 5-digit number (see "make unique pathname" in ${0%.sh}.awk.
# ------------------------------------------------------------------------------
# Regex $EXTRA_DESKTOP_INCLUDE_RE determines which authorized sources
# can generate new desktop files: {'MIME-types', 'SendTo', 'URI', 'mailcap'}.
# ------------------------------------------------------------------------------
# $1-extra_desktop_dir $2-extra_desktop_mimeapps_list
# ------------------------------------------------------------------------------
# Input: TABLE@8: fo mt hp hn rp an na ex
# [A] Either the system or the user's table not both.
# ------------------------------------------------------------------------------
# Output: TABLE@8 of new desktop files followed by the unmodified input table.
# ------------------------------------------------------------------------------
# In the first TABLE@8, fields `mt` through `hn` hold their original values;
# 'dde' is prepended to field `fo`; field `ex` gets the `rp`'s input value,
# which is the original handler's path with space + '%u' or '%f' appended; `rp`
# is replaced with the new .desktop file's path, and `na` gets the name given
# to the 'Name' .desktop key.
# The complete output row is:
# fo: 'dde'+FOLDER, either {'MIME-types','SendTo','URI'}.
# mt: MIMETYPE
# hp: HANDLER_PATH starts with FOLDER'/'.
# hn: HANDLER_NAME is the basename of HANDLER_PATH.
# rp: HANDLER_REAL_PATH is the canonical physical path of the new .desktop file.
# an: APPNAME is a Rox AppDir's basename when HANDLER_PATH is an AppDir/AppRun.
# na: Value of the 'Name' key of the .desktop file.
# ex: Value of the 'Exec' key (trailing Exec %variables erased) of the .desktop
# ------------------------------------------------------------------------------
# [B] We pretend that all desktop files (old ones included) are located in
# $extra_desktop_dir so that update_mimeapps_list can write the _basename_
# to mimeapps.list - see update_mimeapps_list's note [B].
# ---------------------------------------------------------------------------}}}
make_extra_desktop_files () {
	local extra_desktop_dir="${1:?}" extra_desktop_mimeapps_list="${2:?}"

	cprint "Creating extra desktop files in $extra_desktop_dir" >&2

	# TABLE@: fo mt hp hn rp an na ex
	$AWK -f "${0%.sh}.awk" \
		-v "OUT_DIR=$extra_desktop_dir" \
		-v "INCLUDE=^(${EXTRA_DESKTOP_INCLUDE//+/|})$" \
		-v "CATEGORY=$EXTRA_DESKTOP_CATEGORY" \
		-v "ICON=$EXTRA_DESKTOP_ICON" \
		-v "SN=$SN" \
		-v "ROOT=$ROOT" \
		-v "PLAN=$EXTRA_DESKTOP_PLAN" |

		tee >(	# [B]
			$AWK -F $'\037' \
				-v "OUT_DIR=$extra_desktop_dir" \
				-v "DESKTOP_FILE_DIR=${extra_desktop_dir%/*}" '
				BEGIN { OFS = FS; offset = length(DESKTOP_FILE_DIR) +1 }
				/\034(system|user)_begin/,/\034(system|user)_end/ && /^dde/ {
					if (1 == index($5, DESKTOP_FILE_DIR)) {
						$5 = OUT_DIR substr($5, offset) # `rp`
					}
				}
				{print}' |

			PLAN="$EXTRA_DESKTOP_PLAN" update_mimeapps_list \
			"$extra_desktop_dir/$extra_desktop_mimeapps_list" '')

	# concatenated TABLE@: fo mt hp hn rp an na ex
}

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

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

find_best_awk
((is_root=!UID))

exec {table_out_fd}> "$TABLE_OUT"

### split input TABLE@8
tsystem="$TMP-system.csv" tuser="$TMP-user.csv"

$AWK -v "TSYSTEM=$tsystem" -v "TUSER=$tuser" '
/\034system_begin/,/\034system_end/ {print > TSYSTEM}
/\034user_begin/,  /\034user_end/   {print > TUSER}'

### create desktop files

if ((is_root && ! USER_ONLY)); then
	< "$tsystem" make_extra_desktop_files \
		"$EXTRA_DESKTOP_FILE_DIR/$EXTRA_DESKTOP_FOLDER" \
		"$EXTRA_DESKTOP_MIMEAPPS_LIST" >&${table_out_fd}
fi

if ((! SYSTEM_ONLY)); then
	< "$tuser"  make_extra_desktop_files \
		"$LOCAL_DESKTOP_FILE_DIR/$EXTRA_DESKTOP_FOLDER" \
		"$EXTRA_DESKTOP_MIMEAPPS_LIST" >&${table_out_fd}
fi

exec {table_out_fd}>&- # flush output table

# not tracking script status
exit

