#!/bin/sh -efu
# Copyright (c) 2025 Dmitry V. Levin <ldv@strace.io>
# All rights reserved.
#
# SPDX-License-Identifier: LGPL-2.1-or-later

print_help()
{
	cat <<__EOF__
$0 [-d DIR] [--list] [--stdout] FILE [ENUM...]
$0 [-h|--help]

Generate xlat files from enum definitions.

Options:
  -d DIR	Use DIR as a directory for generated xlat files.
  --list        Print all enum names found in the FILE.
  --stdout      Print generated output to stdout.
  -h, --help    Print this message and exit.
__EOF__

exit "$@"
}

print_usage()
{
	print_help 1 >&2
}

dir=src/xlat
list=0
write_stdout=0

while :; do
	case "${1:-}" in
	-d)
		shift
		[ $# -ge 1 ] ||
			print_usage
		dir="$1"
		;;
	--list)
		list=1
		;;
	--stdout)
		write_stdout=1
		;;
	-h|--help)
		print_help 0
		;;
	-*)
		print_usage
		;;
	*)
		break
		;;
	esac

	shift
done

case "$list$#" in
	11) ;;
	00|1*)
		print_usage
		;;
esac

file="$1"; shift
cat "$file" > /dev/null

[ $# -ge 1 ] ||
	set -- $(sed -n 's/^enum \([[:alpha:]][[:alnum:]_]*\) {.*/\1/p' "$file")

gen()
{
	local enum
	enum="enum $table"

	printf '%s\n%s\n' \
		"#Generated by $0 from \"$enum\" in $file; do not edit." \
		'#unconditional'
	sed -n "/^$enum "'{/,/^};/p' "$file" |
		grep -v '_MAX\>' |
		sed 's/= 0,/,/' |
		grep -Fq = ||
		echo '#value_indexed'
	sed -n "/^$enum "'{/,/^};/ s/^[[:space:]]*\([A-Z][[:alnum:]_]*\).*/\1/p' "$file" |
		grep -v '_MAX\>' ||:
}

for table; do
	if [ "$list" = 1 ]; then
		printf '%s\n' "$table"
	elif [ "$write_stdout" = 1 ]; then
		gen
	else
		xlat="$dir/$table.in"
		gen > "$xlat"
		printf '%s\n' "${0##*/}: generated $xlat"
	fi
done
