#!/bin/bash
#
# utf8encode - Given one or more unicode strings, return the
#              underscore-encoded version (one per line).
#

declare -i __UTF8ENCODE_CP1_MAX=16#00007F
declare -i __UTF8ENCODE_CP2_MAX=16#0007FF
declare -i __UTF8ENCODE_CP3_MAX=16#00FFFF
declare -i __UTF8ENCODE_CP4_MAX=16#10FFFF

# Print 2 hex nibs for character with offset pfxlen
# Params:
#   var:    target variable to write nibs into
#   pfxlen: This is the number of leading 1's in the byte
#   value:  Value to encode, must be bit-shifted for multi-byte utf8
#           (6 bits per byte except for the first byte, extra bits
#           will be masked)
__utf8encode_getnibs() {
	local var=$1 pfxlen=$2 value=$3 prefix='2#'
	local -i pshift mask i

	# Generate the utf8 prefix
	for ((i=0; i<pfxlen; i++)); do
		prefix+='1'
	done
	# Trailing 0 (leading when pxflen is 0)
	prefix+='0 << pshift'  # pshift defined below

	# Complement for bit shift: pfxlen + 1
	pshift=$((8 - pfxlen - 1))

	# Value mask - remaining bits
	mask=$((2 ** pshift - 1))

	# Combine prefix & value
	printf -v "$var" '%02x' $((prefix | (value & mask)))
}

# Encode string to escaped utf8, write decoded value to $retval.
# Params:
#   var: String to encode
utf8encode() {
	local var=$1 res='' enc tmp
	local -i i chr plen bits

	for ((i=0; i<${#var}; i++)); do
		printf -v chr '%i' "'${var:i:1}"
		# Match codepoints range to avoid playing with the locale...
		if ((chr >= 97 && chr <= 122)) ||  # [a-z]
		   ((chr >= 65 && chr <= 90))  ||  # [A-Z]
		   ((chr >= 48 && chr <= 57))  ||  # [0-9]
		   ((chr == 46)); then             # .
			res+="${var:i:1}"
		else
			enc='_'
			plen=0  # No prefix for 7-bit, else 2..4
			bits=0  # Not counting the first nibble (so 0 for 7-bit)
			if ((chr > __UTF8ENCODE_CP4_MAX)); then
				echo >&2 "Invalid encoding" # possible?
				return 1
			elif ((chr > __UTF8ENCODE_CP3_MAX)); then
				plen=4
				bits=18  # not counting the first nibble
			elif ((chr > __UTF8ENCODE_CP2_MAX)); then
				plen=3
				bits=12
			elif ((chr > __UTF8ENCODE_CP1_MAX)); then
				plen=2
				bits=6
			fi  # else 7-bit ascii

			__utf8encode_getnibs tmp $plen $((chr >> bits))
			enc+=${tmp:?"Assigned by ref, make shellcheck happy"}

			# Multi-byte only: loop on remaining bits
			for ((bits-=6; bits>=0; bits-=6)); do
				__utf8encode_getnibs tmp 1 $((chr >> bits))
				enc+=$tmp
			done
			res+=$enc
		fi
	done
	printf -v retval '%s' "$res"
}

# test
# set -- _foo⁽™⁾bar🐍

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