#!/bin/bash

# Copyright (C) 2018-2020 Western Digital Corporation or its affiliates
# Copyright (C) 2017-2018 Wearable, Inc.
# Copyright (C) 2000-2012 leJOS Contributors
# Copyright (C) 2000 Jose H. Solorzano and TinyVM Contributors
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# This Source Code Form is “Incompatible With Secondary Licenses”,
# as defined by the Mozilla Public License, v. 2.0.

to_upper()
{
	printf "%s" "$1" | tr '[:lower:]' '[:upper:]'
}

convert_class()
{
	local TMP=$(to_upper "_${1//./_}")
	local LINE

	echo "/* Generated file. Do not modify. */"
	echo "#ifndef $TMP"
	echo "#define $TMP"
	echo
	
	local i=0
	while read -r LINE; do
		if [[ ! "$LINE" =~ ^[[:space:]]*\# ]] && [[ "$LINE" =~ [^[:space:]] ]]; then
			LINE="$(to_upper "$LINE")"
			LINE="${LINE//;/}"
			LINE="${LINE//[/A}"
			LINE="${LINE//\//_}"
			echo "#define $LINE $i"
			let i++
		fi
	done
	echo "#define NUM_SPECIAL_CLASSES $i"
	
	echo
	echo "#endif" 
}

convert_signature()
{
	local TMP=$(to_upper "_${1//./_}")
	local LINE

	echo "/* Generated file. Do not modify. */"
	echo "#ifndef $TMP"
	echo "#define $TMP"
	echo
	
	local i=0
	while read -r LINE; do
		if [[ ! "$LINE" =~ ^[[:space:]]*# ]] && [[ "$LINE" =~ [^[:space:]] ]]; then
			LINE="${LINE//_/_0}"
			LINE="${LINE//[/_1}"
			LINE="${LINE//;/_2}"
			LINE="${LINE//\//_3}"
			LINE="${LINE//(/_4}"
			LINE="${LINE//)/_5}"
			LINE="${LINE//</_6}"
			LINE="${LINE//>/_7}"
            LINE="${LINE//\$/_8}"
			echo "#define $LINE $i"
			let i++
		fi
	done
	
	echo
	echo "#endif" 
}

IN="$2"
OUT="$3"
OUTNAME=$(basename -- "$OUT")

if [ $# != 3 ]
then
	echo Usage: "$0" '[class|signature]' in out
	exit 1
fi

case "$1" in
	class)
		convert_class "$OUTNAME" <"$IN" >"$OUT"
		;;
	signature)
		convert_signature "$OUTNAME" <"$IN" >"$OUT"
		;;
	*)
		echo "unknown type"
		exit 1
esac
