#
# Usage: awk -f fatdog-sync-mime-make-desktop-files.awk \
# 	-v "OUT_DIR=/path/to/new/file/container/" \
# 	-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"

# ------------------------------------------------------------------------------
# Input: TABLE@8: fo mt hp hn rp an na ex
# ------------------------------------------------------------------------------
# Output: TABLE@8 obtained by concatenating a TABLE@8 of the new desktop files
# and the input TABLE@8: update_mimeapps_list expects to read this format.
# See shell function make_extra_desktop_files for details.
# ------------------------------------------------------------------------------
#
BEGIN {
	FS = "\037"

	# no-ops that "declare" arrays - needed to appease mawk
	"" in adata; "" in aid; "" in aseen
	naid = 0
}


{
	R[NR] = $0
	fo=$1; mt=$2; hp=$3; hn=$4; rp=$5; an=$6; na=$7; ex=$8

	## no new desktop file is needed in the following cases:

	if (1 == index(fo, "###")) { # section marks
		split(fo, A, /\034/)
		source[++nsource] = A[3]
		next
	}
	if (fo !~ INCLUDE) { # excluded authorized sources
		next
	}
	if(ex != "") {       # rows already associated to a .desktop file
		next
	}
}

## rows that aren't associated to a .desktop file get a new file
{
	na = an ? an : hn # give it a name
	ex = rp           # move previous handler's path to `ex`

	icon = rp
	if (hn == "AppRun") {
		sub("/[^/]+$", "/.DirIcon", icon)
		if (1 == index(icon, ROOT)) { icon = substr(icon, length(ROOT) + 1) }
	} else if (rp ~ /\.[^.]+$/) {
		icon = ICON
	} else {
		sub(".*/", "", icon)
	}

	o = source[nsource]
	sub("/[^/]+$", "", o)
	origin = o "/" hp

	# NR identifies the new .desktop file
	stash_df(NR, mt, na, ex, icon, origin)
}

END {
	###  create new desktop files and print first output table
	status = -1
	if (length(adata)) {
		fmt = "[Desktop Entry]\nType=Application\nTerminal=false\nNoDisplay=true"
		fmt = fmt "\nCategories=%s;\nName=%s\nExec=%s\nIcon=%s"

		when = strftime()

		for (nr in aid) {
			id  = aid[nr]
			# make unique pathname
			s = tolower(sprintf("%05d_%s", id, adata[id, "name"]))
			gsub(/[[:blank:]]/, "_", s)
			path = OUT_DIR "/" s ".desktop"
			adata[id, "path"] = path

			# create .desktop file
			if (index(PLAN, "desktopfiles")) {
				# try making container dir once only in this loop
				if (status == -1) {
					status = system("mkdir -p \"" OUT_DIR "\"")
					# don't bail out on error
				}
				# write file
				if (status == 0) {
					make_df(aid[nr], when, path)
				}
			}

			# print the corresponding table row - dry-run included
			ofs = OFS; OFS = FS
			$0  = R[nr]
			$1  = "dde" $1          # fo with desktop entry prefix
			$5  = adata[id, "path"] # rp
			$7  = adata[id, "name"] # na
			$8  = adata[id, "ex"]   # ex
			print
			OFS = ofs
			# TABLE@8: `fo` mt hp hn `rp` an `na` `ex`
		}
	}

	### concatenate the unmodified input table
	for(nr = 1; nr <= NR; nr++) {
		print R[nr]
	}

	exit (status)
}

# return .desktop file id and fill globals aid[], naid, adata[], aseen[]
function stash_df(nr, mt, na, ex, icon, origin,    id) {

	if (!((na ":" ex) in aseen)) {
		aid[nr] = id = nr # integer ids aren't necessarily contiguous
		++naid
		aseen[na ":" ex]  = id
		adata[id, "name"] = (1 != index(na, ".") ? na : substr(na, 2))
		adata[id, "exec"] = ex " " (1 == index(mt, "x-scheme-handler/") ?"%u" :"%f")
		adata[id, "ex"]   = ex
		adata[id, "icon"] = icon
	}
	id = aseen[na ":" ex]
	adata[id, "mimetypes"] = adata[id, "mimetypes"] (mt ";")
	adata[id, "origin"] = adata[id, "origin"] (origin "\n")
}

function make_df(id, when, path,   s) {

	# print formatted contents
	s = sprintf(fmt, CATEGORY, adata[id,"name"], adata[id,"exec"], adata[id,"icon"])
	print  s                                                   > path
	print  "MimeType=" adata[id, "mimetypes"]                  > path
	print  "# " "you can edit this file"                       > path
	printf "# created on %s by %s with data from:\n", when, SN > path
	s = adata[id, "origin"]
	gsub(/\n/, "\n# ", s); gsub(/\/AppRun\n/, "\n", s)
	print  "# " s                                              > path
	close(path)
}

