#!/bin/sh

set -euf

generate_header ()
{
	echo "/* WARNING: file is autogenerated */"
	echo ""
	echo "#include <glib.h>"
	echo ""
	echo "#ifndef ${UPPER}_OIDS_"
	echo "#define ${UPPER}_OIDS_"
	echo ""
	echo "void _${LOWER}_oids_init (void);"

	while read name oid; do
		if [ -n "$name" ]; then
			echo "GQuark ${UPPER}_OID_${name};"
		fi
	done

	echo ""
	echo "#endif /* ${UPPER}_OIDS_ */"
}

generate_source ()
{
	echo "/* WARNING: file is autogenerated */"
	echo ""
	echo "#include \"$HEADER\""
	echo ""

	echo "void"
	echo "_${LOWER}_oids_init (void)"
	echo "{"
	echo "	static volatile gsize initialized = 0;"
	echo "	if (g_once_init_enter (&initialized)) {"

	while read name oid; do
		if [ -n "$name" ]; then
			echo "		${UPPER}_OID_${name} = g_quark_from_static_string (\"${oid}\");"
		fi
	done

	echo "		g_once_init_leave (&initialized, 1);"
	echo "	}"
	echo "}"
}

UPPER="PREFIX"
LOWER="prefix"

while getopts 'c:h:p:' arg; do
	case $arg in
	p)
		UPPER=$(echo "$OPTARG" | tr '[:lower:]' '[:upper:]')
		LOWER=$(echo "$OPTARG" | tr '[:upper:]' '[:lower:]')
		;;
	c)
		SOURCE="$OPTARG"
		;;
	h)
		HEADER="$OPTARG"
		;;
	*)
		echo "gcr-mkoids: invalid argument: $arg" >&2
		exit 2
		;;
	esac
done

shift $(expr $OPTIND - 1)
if [ $# -ne 1 ]; then
	echo "gcr-mkoids: specify input file on command line"
	exit 2
fi

INPUT="$1"

if [ -n "$HEADER" ]; then
	generate_header < $INPUT > $HEADER
fi
if [ -n "$SOURCE" ]; then
	generate_source  < $INPUT > $SOURCE
fi
