#!/bin/sh

. /lib/functions.sh
. /usr/share/libubox/jshn.sh

backend_sysfs="/sys/class/tty/ttyAudio0/backend_tty"
splitter_audio="/dev/ttyAudio0"
modem_audio=""
tty_data=""
active_audio=""
module_name="asterisk-snd-split"

ME="asterisk-chan-quectel"
LOGGER="/usr/bin/logger -p daemon.err -s -t $ME --"

if [ "$EVENT_NAME" = "gsm.new_modem" ]; then
	$LOGGER "gsm modem event: $EVENT_NAME $OBJECT_NAME"

	me_en="$(jsonfilter -q -i /etc/board.json -e "@.hwinfo[\"asterisk\"]" 2>/dev/null)"
	if [ "$me_en" != "true" ]; then
		$LOGGER "Feature \"$ME\" is not supported on this device."
		exit 0
	fi

	# OBJECT_NAME comes from the gsmd hotplug event. Constrain it to the
	# expected "gsm.modemN" object path before using it as a ubus target
	# (and quote it everywhere) so a malformed value can't word-split into
	# extra ubus arguments.
	case "$OBJECT_NAME" in
		gsm.modem[0-9]*) ;;
		*)
			$LOGGER "unexpected modem object '$OBJECT_NAME', ignoring"
			exit 0
			;;
	esac

	if ! info_json="$(ubus call "$OBJECT_NAME" info 2>/dev/null)"; then
		$LOGGER "failed to get $OBJECT_NAME info"
		exit 0
	fi

	# Parse with json_load (jshn.sh) instead of eval'ing jshn -r output —
	# never eval a ubus response.
	if ! json_load "$info_json" 2>/dev/null; then
		$LOGGER "failed to parse $OBJECT_NAME info"
		exit 0
	fi

	json_get_var modem_audio gps_port
	json_get_var tty_data data_port

	if [ -z "$modem_audio" ] || [ -z "$tty_data" ]; then
		$LOGGER "missing modem ports: gps_port and data_port must be set in $OBJECT_NAME info"
		exit 0
	fi

	# gps_port/data_port are written to sysfs, embedded in a sed
	# replacement and chowned below — constrain them to real TTY device
	# paths so a malformed value can't retarget any of those operations.
	for _port in "$modem_audio" "$tty_data"; do
		case "$_port" in
			/dev/tty*) ;;
			*)
				$LOGGER "rejecting non-TTY modem port '$_port'"
				exit 0
				;;
		esac
	done

	# route audio through the GNSS/audio splitter when it is present
	[ -w "$backend_sysfs" ] || modprobe "$module_name" 2>/dev/null || true
	if [ -w "$backend_sysfs" ]; then
		echo "${modem_audio}" > "$backend_sysfs"
		active_audio="$splitter_audio"
	else
		active_audio="$modem_audio"
	fi

	if [ -w /etc/asterisk/quectel.conf ]; then
		sed -i -E "s|^[[:space:];]*audio[[:space:]]*=.*$|audio=${active_audio}|" /etc/asterisk/quectel.conf
		sed -i -E "s|^[[:space:];]*data[[:space:]]*=.*$|data=${tty_data}|" /etc/asterisk/quectel.conf
	else
		$LOGGER "missing or non writable config file: /etc/asterisk/quectel.conf"
		exit 0
	fi

	for devnode in "$active_audio" "$tty_data"; do
		[ -e "$devnode" ] || continue
		chown asterisk:asterisk "$devnode"
		chmod 0660 "$devnode"
	done

	if [ -x /etc/init.d/asterisk ] && /etc/init.d/asterisk running >/dev/null 2>&1; then
		/etc/init.d/asterisk reload
		# asterisk -x "quectel restart now quectel0"
	fi

	$LOGGER "gsm modem audio: $active_audio, backend: $modem_audio, data: $tty_data"

elif [ "$EVENT_NAME" = "gsm.modem_gone" ]; then
	$LOGGER "gsm modem event: $EVENT_NAME $OBJECT_NAME"

	if [ -x /etc/init.d/asterisk ] && /etc/init.d/asterisk running >/dev/null 2>&1; then
		asterisk -x "quectel stop now quectel0"
	fi

	spl_en="$(jsonfilter -q -i /etc/board.json -e "@.hwinfo[\"asterisk\"]" 2>/dev/null)"
	if [ "$spl_en" = "true" ] && [ -w "$backend_sysfs" ]; then
		echo "" > "$backend_sysfs"
	elif [ "$spl_en" = "true" ]; then
		$LOGGER "missing backend sysfs control: $backend_sysfs"
	fi
fi
