#!/bin/bash
#
# utf8decode - Given one or more underscore-encoded utf8 strings, return
#              the decoded UTF-8 version (one per line).
#

# Check parameter is valid hex
# Params:
#   $1: hex value to check
__utf8decode_isnib() {
	case $1 in
		[0-9A-Fa-f][0-9A-Fa-f])
			return 0
			;;
		*)
			echo >&2 "Invalid encoding: $1 is not hex"
			return 1
	esac
}

# Check a nibble starts with 0b >>10<< 00 0000
# Params:
#   val: hex value to check
__utf8decode_checknib() {
	local -i val=16#$1

	# if/else seems to be a tad faster than default fail
	if ((val >> 6 == 1 << 1)); then
		return 0
	else
		echo >&2 "Invalid encoding: 0x$1"
		return 1
	fi
}

# Decode utf8-encoded string, write decoded value to $retval.
# Params:
#   var: Value to decode
utf8decode() {
	local var=$1 res='' char tmp
	local -i chr i j

	for ((i=0; i<${#var};)); do
		char=${var:i++:1}
		if [ "$char" = _ ]; then
			# Get first byte
			tmp=${var:i+=2,i-2:2}
			__utf8decode_isnib "$tmp" || return 1
			char="\\x$tmp"
			chr=16#$tmp

			if ((chr >= 192)); then
				# Multi-byte header (0b11xxxxxx)

				for ((j=7; j>3; j--)); do
					# Read one additional byte for each 1 in prefix
					((chr >> j & 1)) || break
					((j == 7)) && continue  # We have the first byte already

					# Read next byte
					tmp=${var:i+=2,i-2:2}
					__utf8decode_isnib "$tmp" || return 1
					__utf8decode_checknib "$tmp" || return 1
					char+="\\x$tmp"
				done

				# Prefix cannot have more that 4 1's (0b1111 1000)
				if ((chr >> j & 1)); then
					echo >&2 "Invalid encoding: 0x$tmp"
					return 1
				fi
			elif ((chr > 127)); then
				# 128-191 aren't valid for the first byte (0b10xxxxxx)
				echo >&2 "Invalid encoding: 0x$tmp"
				return 1
			fi

			char=${char@E}
			# This is a lazy way of failing on the High Surrogates (U+D800 - DB7F),
			# High Private Use Surrogates (U+DB80 - U+DBFF) and Low Surrogates
			# (U+DC00 - U+DFFF). Even using the $'\Uxxxx' syntax bash seems to
			# encode it to hex and interpret it as whatever encoding that fits, like
			# iso-8859-1!!. Then we get >1 character...
			[ ${#char} -gt 1 ] && echo >&2 "Invalid encoding: $char" && return 1
		fi
		res+=$char
	done
	printf -v retval '%s' "$res"
}

# test
# set -- _5ffoo_e281bd_e284a2_e281bebar_f09f908d

for arg in "$@"; do
	utf8decode "$arg"
	printf '%s\n' "$retval"
done
