#!/bin/sh
#
# Wrapper around /usr/bin/sms_tool that re-encodes its output from
# Latin-1 (ISO-8859-1) to UTF-8 so accented characters render correctly
# in the LuCI app. Upstream sms_tool emits 8-bit bytes (0x80-0xFF) for
# GSM/UCS-2 chars in the Latin-1 range without converting to UTF-8.
#
# The awk filter walks the input byte-by-byte. ASCII (<0x80) is passed
# through unchanged; bytes 0x80-0xFF are turned into the canonical
# two-byte UTF-8 sequence (0xC0|c>>6, 0x80|c&0x3F).
#

/usr/bin/sms_tool "$@" 2>/dev/null | awk '
BEGIN {
	for (i = 128; i < 256; i++) {
		b1 = 192 + int(i / 64)
		b2 = 128 + (i % 64)
		u8[sprintf("%c", i)] = sprintf("%c%c", b1, b2)
	}
	RS = ""
}
{
	out = ""
	n = length($0)
	for (j = 1; j <= n; j++) {
		c = substr($0, j, 1)
		if (c in u8) out = out u8[c]
		else out = out c
	}
	printf "%s", out
}
'
