#!/bin/sh

set -e

# http://www.iq0.com/duffgram/com.html implementation
# (consulted source to see what -n did)

arv0="$0"; shell='sh -c'

usage(){
	printf 'Usage: %s (-n) (file...)\n' "$argv0" >&2
	exit 64	# sysexits(3) EX_USAGE
}

for arg in "$@"
do
	printf '%s\n' "$arg" \
		| grep '^-' >/dev/null 2>&1 \
			|| break
	shift
	printf '%s\n' "$arg" \
		| grep 'n' >/dev/null 2>&1 \
			&& shell=echo \
			|| true
	printf '%s\n' "$arg" \
		| grep '[^-n]' >/dev/null 2>&1 \
			&& usage \
			|| true
	printf '%s\n' "$arg" \
		| grep -- '-.*-' >/dev/null 2>&1 \
			&& break \
			|| true
done

test -n "$1" \
	|| set -- "$(cat .comfile 2>/dev/null)" \
	&& test -n "$1" \
	|| usage

>.comfile

awk -v argv0="$argv0" -v shell="$shell" '
# https://www.gnu.org/software/gawk/manual/html_node/Filetrans-Function.html
FILENAME != current_file {
	processed = 0;
	if(current_file != 0){
		print current_file >>".comfile";
		if(cmd == ""){
			# https://www.gnu.org/software/gawk/manual/html_node/
			#	Special-FD.html
			printf("%s: no command\n", ARGV[2]) >"/dev/stderr";
			exit 65 # sysexits(3) EX_DATAERR
		}else{
			print cmd | shell;
			cmd = "";
		}
	}
	current_file = FILENAME;
}
cmd == "" && /\/\*%/ {
	sub(/.*\/\*%[:space:]*/, "");
	stem = FILENAME;
	sub(/\.[^.]*$/, "", stem);
	for(i = 0; i < length($0) - 1; ++i)
		cmd = cmd ((substr($0, i, 2) == "##" || substr($0, i, 2) == "%%") \
			? substr($0, i++, 1) \
			: (substr($0, i, 1) == "%") \
				? FILENAME \
				: (substr($0, i, 1) == "#") \
					? stem \
					: substr($0, i, 1)) \
		;
	cmd = cmd substr($0, i, 2);
}
END {
	print current_file >>".comfile";
	if(cmd != "")
		print cmd | shell;
	if(processed == 0){
		printf("%s: no command\n", argv0) > "/dev/stderr";
		exit 65; # sysexits(3) EX_DATAERR
	}
}
	'
