#!/bin/sh
# Xiaomi R1350 Internet LED state machine, ported from stock check_wan_status.lua.
# Stock behavior: no WAN link=off, no Internet=yellow, Internet=blue; 8 second interval.

PATH=/usr/sbin:/usr/bin:/sbin:/bin
YELLOW=/sys/class/leds/yellow:function/brightness
BLUE=/sys/class/leds/blue:function/brightness
LAST=""

set_led() {
	[ "$1" = "$LAST" ] && return
	LAST="$1"
	case "$1" in
		off)
			echo 0 > "$YELLOW"; echo 0 > "$BLUE"
			;;
		yellow)
			echo 0 > "$BLUE"; echo 1 > "$YELLOW"
			;;
		blue)
			echo 0 > "$YELLOW"; echo 1 > "$BLUE"
			;;
	esac
	logger -t r1350-wan-led "WAN LED state: $1"
}

wan_link_up() {
	# Stock R1350 explicitly checks switch port 1.
	swconfig dev switch0 port 1 get link 2>/dev/null | grep -q 'link:up'
}

dns_up() {
	for host in api.miwifi.com www.baidu.com www.taobao.com; do
		nslookup "$host" 2>/dev/null | grep -E '^Address( [0-9]+)?:' | \
			grep -Ev '(:|127\.0\.0\.1|^Address( [0-9]+)?: 10\.|^Address( [0-9]+)?: 192\.168\.|^Address( [0-9]+)?: 172\.|^Address( [0-9]+)?: 169\.254\.)' >/dev/null && return 0
	done
	return 1
}

ping_up() {
	for ip in 114.114.114.114 180.76.76.76 119.29.29.29 223.5.5.5; do
		ping -4 -c 1 -W 1 "$ip" >/dev/null 2>&1 && return 0
	done
	return 1
}

trap 'set_led off; exit 0' TERM INT

while :; do
	if ! wan_link_up; then
		set_led off
	elif dns_up; then
		set_led blue
	else
		# Stock probes IPs after DNS failure, but router mode remains yellow when
		# DNS is broken even if an IP responds. Keep that exact user-visible state.
		ping_up >/dev/null 2>&1
		set_led yellow
	fi
	sleep 8
done
