#!/bin/sh

readonly LANG=C
readonly PKGNAME=$(make -V PKGNAME 2>/dev/null)
readonly PREFIX=$(make -V PREFIX 2>/dev/null)
plist_file=$1

if [ ! "$PKGNAME" -o ! "$PREFIX" ]; then
	echo "===> This is not port directory" >&2
	exit 1
fi

[ "$plist_file" ] || plist_file=$(make -V PLIST)
if [ ! -f "$plist_file" ]; then
	echo "===> Plist file was not found: $plist_file" >&2
	exit 1
fi

options_subs="PORTDOCS PORTEXAMPLES"
for sub in $(make -V PLIST_SUB); do
	case $sub in *@comment*)
		case $sub in NO_*) sub=${sub##NO_}; esac
		options_subs="$options_subs ${sub%%=*}"
	esac
done

awk -v prefix="$PREFIX/" -v plist_subs="$(make -V PLIST_SUB)" \
	-v options_subs="$options_subs" '
BEGIN {
	separator="###";

	n = split(options_subs, s_array, " ");
	for (i=1; i<=n; i++)
		opt_subs[s_array[i]] = s_array[i];

	n = split(plist_subs, array, " ");
	for (pair=1; pair<=n; pair++) {
		if (split(array[pair], p_array, "=") != 2)
			continue;
		if (p_array[1] in opt_subs)
			continue;
		gsub("\"", "", p_array[2]);
		if (p_array[2] && p_array[2] != "@comment")
			subs[p_array[1]] = p_array[2];
	}
}

function store_pathname(path, tokens) {
	is_dir = match(tokens, "@dir");

	if (match(path, "^/")) # nonprefix items
		(is_dir) ? dirs_np[path] = tokens : files_np[path] = tokens;
	else
		(is_dir) ? dirs[path] = tokens : files[path] = tokens;
}

function str_replace(string, pattern, new_pattern) {
	str="";

	if ((sr_fields = split(string, sr_array, pattern)) == 1)
		return string;
	for (sr_index=1; sr_index <= sr_fields; sr_index++) {
		if (sr_index != sr_fields)
			str = str sr_array[sr_index] new_pattern;
		else
			str = str sr_array[sr_index];
	}
	return str;
}

function plist_split(string, out) {
	pos = index(string, " ");
	out[1] = substr(string,1, pos-1);
	out[2] = substr(string, pos+1);
}

function keyword_line_tokenize(line, keyword) {
	path = "";
	# little hack to get depth first sorting order
	suffix = (keyword == "dir") ? "zzz" : "";

	if ((n = split(line, array, "%%")) == 1) {
		plist_split(array[1], p);
		store_pathname(p[2], p[2] suffix separator line);
		return;
	}

	for (i=1; i <= n; i++) {
		if (match(array[i], "^@" keyword)) {
			plist_split(array[i], p);
			path = p[2];
			continue;
		}

		if (array[i] in opt_subs)
			continue;

		path = (array[i] in subs) ? path subs[array[i]] : path array[i];
	}

	store_pathname(path, path suffix separator line);
}

function sort_to_file(array, file) {
	for (i in array) print array[i] | ("sort -u >" file);
	close("sort -u >" file);
}

function truncate_file(file) {
	close(file);
	system("cat /dev/null>" file);
}

function print_files(array, file) {
	sort_to_file(array, file);

	while((getline line < file) > 0)
		if ((n = split(line, p, separator)) == 2)
			print p[2];
		else
			print line;

	truncate_file(file);
}

function print_dirs(array, file) {
	sort_to_file(array, file);

	while((getline line < file) > 0)
		if ((n = split(line, p, separator)) == 2)
			print p[2];

	truncate_file(file);
}

/^(%%[0-9A-Z_]*%%)*([a-z]|\/)+/ { # files
	path = "";

	if ((n = split($0, array, "%%")) == 1) {
		store_pathname($0, $0);
		next;
	}

	for (i=1; i <= n; i++) {
		if (array[i] in opt_subs)
			continue;

		path = (array[i] in subs) ? path subs[array[i]] : path array[i];
	}

	store_pathname(path, path separator $0);
}

/^@comment/ {
	cmds[++n_cmds] = $0;
}

/^(%%[0-9A-Z_]*%%)*@dir/ { # dirs
	keyword_line_tokenize($0, "dir");
}

/^(%%[0-9A-Z_]*%%)*@rmtry/ {
	keyword_line_tokenize($0, "rmtry");
}

/^(%%[0-9A-Z_]*%%)*@sample/ {
	keyword_line_tokenize($0, "sample");
}

/^(%%[0-9A-Z_]*%%)*@\(.*\)/ { # @(owner,group,mode) path
	keyword_line_tokenize($0, "");
}

/^(%%[0-9A-Z_]*%%)*@/ { # other commands, @exec, @unexec etc
	if (match($0, "@(comment|dir|rmtry|sample)") || match($0, "@\\(.*\\)"))
		next;

	cmds[++n_cmds] = $0;
}

END {
	"mktemp -t plist-sort" | getline tmpfile;
	close("mktemp -t plist-sort");

	print_files(files, tmpfile);
	print_files(files_np, tmpfile);
	print_dirs(dirs, tmpfile);
	print_dirs(dirs_np, tmpfile);
	system("rm " tmpfile);

	for (i in cmds)
		print cmds[i];
}' "$plist_file"
