#!/bin/sh
# rpcd plugin for modem-man
# ubus object: modem-man
# Methods: status, reconnect, info

. /usr/share/libubox/jshn.sh

MM_RUNDIR="/var/run/modem-man"

# Читаем статус netifd-интерфейса через ubus
_iface_status() {
	local iface="$1"
	ubus call "network.interface.$iface" status 2>/dev/null
}

# Получаем IP-адреса интерфейса
_get_ip() {
	local iface="$1"
	local addrs
	addrs=$(ip -4 addr show "$iface" 2>/dev/null | awk '/inet /{print $2}' | head -1)
	echo "${addrs:-}"
}

case "$1" in
	list)
		echo '{
  "status":    {},
  "reconnect": {"iface":"String"},
  "info":      {}
}'
		;;
	call)
		case "$2" in

			# ─── status ────────────────────────────────────────────────────────
			status)
				json_init
				json_add_array "modems"

				# Перебираем все секции из UCI modem-man
				config_load_done=0
				. /lib/functions.sh

				_do_modem() {
					local cfg="$1"
					local enabled type netifd_iface ping_host ping_interval watchdog
					config_get enabled       "$cfg" enabled       0
					config_get type          "$cfg" type          ""
					config_get netifd_iface  "$cfg" netifd_iface  ""
					config_get ping_host     "$cfg" ping_host     "8.8.8.8"
					config_get ping_interval "$cfg" ping_interval 30
					config_get watchdog      "$cfg" watchdog      0

					json_add_object ""
					json_add_string  "name"          "$cfg"
					json_add_string  "type"          "$type"
					json_add_boolean "enabled"       "$enabled"
					json_add_string  "netifd_iface"  "$netifd_iface"
					json_add_boolean "watchdog"      "$watchdog"

					# Статус из runtime-файла
					local runfile="$MM_RUNDIR/${cfg}.json"
					local mm_up="false"
					if [ -f "$runfile" ]; then
						local up_val ifname_val
						up_val=$(jsonfilter -i "$runfile" -e '@.up' 2>/dev/null)
						ifname_val=$(jsonfilter -i "$runfile" -e '@.ifname' 2>/dev/null)
						[ "$up_val" = "true" ] && mm_up="true"
						[ -n "$ifname_val" ] && json_add_string "ifname" "$ifname_val"
						for k in level fails last_ok last_action_ts; do
							v=$(jsonfilter -i "$runfile" -e "@.$k" 2>/dev/null); [ -n "$v" ] && json_add_int "$k" "$v"
						done
						for k in message last_action probe; do
							v=$(jsonfilter -i "$runfile" -e "@.$k" 2>/dev/null); [ -n "$v" ] && json_add_string "$k" "$v"
						done
					fi
					json_add_boolean "up" "$([ "$mm_up" = "true" ] && echo 1 || echo 0)"

					# IP-адрес сетевого интерфейса
					if [ -n "$netifd_iface" ]; then
						local iface_json l3dev
						iface_json=$(_iface_status "$netifd_iface")
						if [ -n "$iface_json" ]; then
							l3dev=$(echo "$iface_json" | jsonfilter -e '@.l3_device' 2>/dev/null)
							[ -n "$l3dev" ] && {
								local ipv4
								ipv4=$(_get_ip "$l3dev")
								[ -n "$ipv4" ] && json_add_string "ipv4" "$ipv4"
								json_add_string "l3_device" "$l3dev"
							}
						fi
					fi

					# Сигнал из ubus mainmodem/auxmodem
					local ubus_obj
					case "$cfg" in
						main) ubus_obj="mainmodem" ;;
						aux)  ubus_obj="auxmodem"  ;;
						*)    ubus_obj=""           ;;
					esac
					if [ -n "$ubus_obj" ]; then
						local sig_json
						sig_json=$(ubus call "$ubus_obj" signal 2>/dev/null)
						if [ -n "$sig_json" ]; then
							json_add_object "signal"
							# Пытаемся достать RSRP, RSRQ, SINR, band
							local rsrp rsrq sinr band
							rsrp=$(echo "$sig_json" | jsonfilter -e '@.serving.rsrp' 2>/dev/null)
							rsrq=$(echo "$sig_json" | jsonfilter -e '@.serving.rsrq' 2>/dev/null)
							sinr=$(echo "$sig_json" | jsonfilter -e '@.serving.sinr' 2>/dev/null)
							band=$(echo "$sig_json" | jsonfilter -e '@.serving.band' 2>/dev/null)
							rssi=$(echo "$sig_json" | jsonfilter -e '@.serving.rssi' 2>/dev/null)
							[ -n "$rsrp" ] && json_add_int "rsrp" "$rsrp"
							[ -n "$rsrq" ] && json_add_int "rsrq" "$rsrq"
							[ -n "$sinr" ] && json_add_int "sinr" "$sinr"
							[ -n "$band" ] && json_add_int "band" "$band"
							[ -n "$rssi" ] && json_add_int "rssi" "$rssi"
							json_close_object
						fi
					fi

					json_close_object
				}

				config_load modem-man
				config_foreach _do_modem modem

				json_close_array
				json_dump
				;;

			# ─── reconnect ─────────────────────────────────────────────────────
			reconnect)
				read -r input
				json_load "$input"
				json_get_var target_iface iface

				json_init

				if [ -z "$target_iface" ]; then
					json_add_boolean "success" 0
					json_add_string  "error"   "Parameter 'iface' is required"
					json_dump
					exit 0
				fi

				# Проверяем, что интерфейс существует в UCI
				if ! uci -q get "network.$target_iface" > /dev/null 2>&1; then
					json_add_boolean "success" 0
					json_add_string  "error"   "Interface '$target_iface' not found in UCI network"
					json_dump
					exit 0
				fi

				# Реконнект в фоне (ifdown/ifup блокирующий).
				# notify_proto action=5 сбрасывает proto_set_available 0 — без этого
				# netifd молча игнорирует ifup если интерфейс помечен недоступным
				# (например, после таймаута NO_IFACE в modemman.sh).
				(
					ubus call "network.interface.$target_iface" notify_proto \
						'{"action":5,"available":true}' 2>/dev/null
					ifdown "$target_iface" 2>/dev/null
					sleep 2
					ifup  "$target_iface" 2>/dev/null
				) &

				json_add_boolean "success" 1
				json_add_string  "iface"   "$target_iface"
				json_add_string  "message" "Reconnecting in background"
				json_dump
				;;

			# ─── info ──────────────────────────────────────────────────────────
			info)
				json_init

				# Версия/дата скрипта
				json_add_string "version"    "1.0"
				json_add_string "proto"      "modemman"
				json_add_string "proto_file" "/lib/netifd/proto/modemman.sh"
				json_add_string "watchdog"   "/usr/bin/modem-man"
				json_add_string "config"     "/etc/config/modem-man"
				json_add_string "rundir"     "$MM_RUNDIR"

				# Статус watchdog-процесса
				wd_pid=$(pidof modem-man 2>/dev/null | awk '{print $1}')
				if [ -n "$wd_pid" ]; then
					json_add_boolean "watchdog_running" 1
					json_add_int     "watchdog_pid"     "$wd_pid"
				else
					json_add_boolean "watchdog_running" 0
				fi

				# ModemManager — запущен ли ещё?
				mm_pid=$(pidof ModemManager 2>/dev/null | awk '{print $1}')
				if [ -n "$mm_pid" ]; then
					json_add_boolean "modemmanager_running" 1
					json_add_int     "modemmanager_pid"     "$mm_pid"
				else
					json_add_boolean "modemmanager_running" 0
				fi

				# Краткая инфо по каждому модему
				json_add_array "modems"

				_info_modem() {
					local cfg="$1"
					local type device netifd_iface enabled
					config_get type         "$cfg" type         ""
					config_get device       "$cfg" device       ""
					config_get netifd_iface "$cfg" netifd_iface ""
					config_get enabled      "$cfg" enabled      0

					json_add_object ""
					json_add_string  "name"          "$cfg"
					json_add_string  "type"          "$type"
					json_add_boolean "enabled"       "$enabled"
					json_add_string  "netifd_iface"  "$netifd_iface"

					local ubus_obj
					case "$cfg" in
						main) ubus_obj="mainmodem" ;;
						aux)  ubus_obj="auxmodem"  ;;
						*)    ubus_obj=""           ;;
					esac

					if [ -n "$ubus_obj" ]; then
						local info_json uptime port connected sim_slot
						info_json=$(ubus call "$ubus_obj" info 2>/dev/null)
						if [ -n "$info_json" ]; then
							connected=$(echo "$info_json" | jsonfilter -e '@.connected'  2>/dev/null)
							port=$(echo      "$info_json" | jsonfilter -e '@.port'       2>/dev/null)
							uptime=$(echo    "$info_json" | jsonfilter -e '@.uptime'     2>/dev/null)
							sim_slot=$(echo  "$info_json" | jsonfilter -e '@.sim_slot'   2>/dev/null)
							[ -n "$port"     ] && json_add_string  "at_port"    "$port"
							[ -n "$uptime"   ] && json_add_int     "daemon_uptime" "$uptime"
							[ -n "$sim_slot" ] && json_add_int     "sim_slot"   "$sim_slot"
							json_add_boolean "daemon_connected" "$([ "$connected" = "true" ] && echo 1 || echo 0)"
						fi
					fi

					json_close_object
				}

				. /lib/functions.sh
				config_load modem-man
				config_foreach _info_modem modem

				json_close_array
				json_dump
				;;

		esac
		;;
esac
