#!/bin/sh
#
# Hotplug script for main-modem: maintains /dev/mainmodem_at -> AT-primary port
# of the Quectel RM520N-GL.
#
# The USB interface NUMBER of the AT port is NOT stable: it shifts with the
# usbnet data composition. In QMI mode (the target) the layout is
#   0=DIAG 1=NMEA 2=AT 3=Modem 4=QMI/RMNET, so AT = interface 02; but in
# RNDIS/ECM/MBIM the data function adds interface(s) ahead of the serial ports
# and everything shifts (e.g. RNDIS -> AT = interface 04). The old code keyed on
# interface number 02/00 and therefore latched onto the DIAG port (which does
# not answer AT) whenever the modem booted in a non-QMI composition, leaving the
# daemon unable to talk to the modem (and thus unable to switch it back to QMI).
#
# So identify the AT port by its USB interface DESCRIPTOR, which is intrinsic to
# the port function and composition-independent:
#
#   DIAG    = ff / ff / 30
#   NMEA    = ff / 00 / 40
#   AT prim = ff / 00 / 00   <- lowest-numbered such interface
#   Modem   = ff / 00 / 00
#
# Picking the lowest-numbered ff/00/00 interface yields AT-primary (not the
# Modem/PPP port), in any composition including the reduced 2-interface config.

MAINMODEM_VID="2c7c"
MAINMODEM_PID="0801"

[ "$ACTION" = add ] || [ "$ACTION" = remove ] || return 0

case "$DEVICENAME" in
	ttyUSB*) ;;
	*) return 0 ;;
esac

# Resolve USB device dir from DEVPATH:
#   .../usb1/1-1/1-1:1.4/ttyUSB2/tty/ttyUSB2  ->  .../usb1/1-1
USB_INTF_DIR="/sys$(echo "$DEVPATH" | sed 's|/ttyUSB[0-9]*/tty/ttyUSB[0-9]*$||')"
USB_DEV_DIR="$(dirname "$USB_INTF_DIR")"

VID="$(cat "$USB_DEV_DIR/idVendor" 2>/dev/null)"
PID="$(cat "$USB_DEV_DIR/idProduct" 2>/dev/null)"

[ "$VID" = "$MAINMODEM_VID" ] || return 0
[ "$PID" = "$MAINMODEM_PID" ] || return 0

# Lowest-numbered ff/00/00 (AT-primary) ttyUSB of this modem.
find_at_tty() {
	local d t num cls sub pro tty best_num="" best_tty=""
	for d in "$USB_DEV_DIR"/*:*/; do
		[ -d "$d" ] || continue
		cls="$(cat "$d/bInterfaceClass" 2>/dev/null)"
		sub="$(cat "$d/bInterfaceSubClass" 2>/dev/null)"
		pro="$(cat "$d/bInterfaceProtocol" 2>/dev/null)"
		[ "$cls" = "ff" ] && [ "$sub" = "00" ] && [ "$pro" = "00" ] || continue
		tty=""
		for t in "$d"ttyUSB*; do
			[ -e "$t" ] && tty="$(basename "$t")" && break
		done
		[ -n "$tty" ] || continue
		num="$(cat "$d/bInterfaceNumber" 2>/dev/null)"
		if [ -z "$best_num" ] || [ "$((0x$num))" -lt "$((0x$best_num))" ]; then
			best_num="$num"
			best_tty="$tty"
		fi
	done
	[ -n "$best_tty" ] && echo "$best_tty"
}

apply_symlink() {
	local at_tty="$1"
	[ "$(readlink /dev/mainmodem_at 2>/dev/null)" = "/dev/$at_tty" ] && return 0
	ln -sf "/dev/$at_tty" /dev/mainmodem_at
	logger -t mainmodem "symlink /dev/mainmodem_at -> /dev/$at_tty"

	# USB endpoint reduction and 4x4 MIMO — idempotent, persist in modem NVM
	if ubus list mainmodem >/dev/null 2>&1; then
		ubus call mainmodem usb_check       >/dev/null 2>&1 &
		ubus call mainmodem diversity_check >/dev/null 2>&1 &
	fi

	# Restart service if enabled
	if /etc/init.d/mainmodem enabled 2>/dev/null; then
		uci set mainmodem.main.tty_port="/dev/mainmodem_at"
		uci commit mainmodem
		/etc/init.d/mainmodem restart
	fi
}

case "$ACTION" in
	add)
		AT_TTY="$(find_at_tty)"
		[ -n "$AT_TTY" ] || return 0
		apply_symlink "$AT_TTY"
		;;
	remove)
		# Re-point to a surviving AT port, or drop the symlink if none remain.
		AT_TTY="$(find_at_tty)"
		if [ -n "$AT_TTY" ]; then
			apply_symlink "$AT_TTY"
		elif [ "$(readlink /dev/mainmodem_at 2>/dev/null)" = "/dev/$DEVICENAME" ]; then
			rm -f /dev/mainmodem_at
			logger -t mainmodem "symlink /dev/mainmodem_at removed"
		fi
		;;
esac
