#!/bin/sh

# $1: 0-off, 1-on
fan_normal_led_set() {
	echo $1 > /sys/class/leds/FAN_NORMAL_LED/brightness
}

# $1: 0-off, 1-on
fan_error_led_set() {
	echo $1 > /sys/class/leds/FAN_ERROR_LED/brightness
}

# $1: 0-off, 1-on
fan_led_set() {
	fan_normal_led_set $1
	fan_error_led_set $1
}

fan_led_refresh() {
	
	#local gpio=$(uci get system.fan_state.gpio)
	local fan_state=$(cat /tmp/fan_state)  
	if [ "$fan_state" == "0" ]; then
		fan_normal_led_set 0
		fan_error_led_set 1
	else
		fan_normal_led_set 1
		fan_error_led_set 0
	fi

}

# $1: 0-off, 1-on
usb_lte_led_set() {
	echo $1 > /sys/class/leds/USB_LTE_LED/brightness
}

# $1: 0-off, 1-on
usb_storage_led_set() {
	echo $1 > /sys/class/leds/USB_STORAGE_LED/brightness
}

usb_led_refresh() {
	lte_state=$(cat /tmp/usbLte/USB_PLUGIN)
	# 当modem加载驱动时，hotplug会收到设备拔出消息，此时读取modem_state，否则led被关闭
	modem_state=$(cat /tmp/modem/USB_PLUGIN)
	storage_state=$(cat /tmp/usbStorage/USB_PLUGIN)
	if [ "$lte_state" = "1" ] || [ "$modem_state" = "1" ]; then
		usb_lte_led_set 1
	else
		usb_lte_led_set 0
	fi
	if [ "$storage_state" = "1" ]; then
		usb_storage_led_set 1
	else
		usb_storage_led_set 0
	fi
}

#	pg	su	result
#	0	*	Bad
#	1	0	Good
#	1	1	Supplying
rps_monitor() {
	mkdir -p /tmp/rps_monitor
	
	pwr1_pg_gpio=$(uci get system.pwr1_pg.gpio)
	pwr2_pg_gpio=$(uci get system.pwr2_pg.gpio)
	pwr1_su_gpio=$(uci get system.pwr1_su.gpio)
	pwr2_su_gpio=$(uci get system.pwr2_su.gpio)
	pwr1_pg=$(cat /sys/class/gpio/gpio$pwr1_pg_gpio/value)
	pwr2_pg=$(cat /sys/class/gpio/gpio$pwr2_pg_gpio/value)
	pwr1_su=$(cat /sys/class/gpio/gpio$pwr1_su_gpio/value)
	pwr2_su=$(cat /sys/class/gpio/gpio$pwr2_su_gpio/value)
	[ -e /tmp/rps_monitor/state ] || touch /tmp/rps_monitor/state
	# RPS状态存储在临时文件state中
	# 后台需要按照"$pg$su, $pg$su, ..."的格式解析后传递给前端
	# 前端需要按照"PWR1(Supplying), PWR2(Good), PWR3(Bad),..."的形式显示
	echo "$pwr1_pg$pwr1_su,$pwr2_pg$pwr2_su" > /tmp/rps_monitor/state
}

check_xhci() {
	xhci_state=0
	xhci_state=$(cat /sys/kernel/debug/xhci_status)
	if [ $? != 0 ]; then
		insmod xhci-hcd.ko
		insmod xhci-pci.ko
		insmod xhci-plat-hcd.ko
	else
		if [ $xhci_state = 1 ]; then
			rmmod xhci-plat-hcd.ko
			insmod xhci-plat-hcd.ko
			echo 0 > /sys/kernel/debug/xhci_status
		fi
	fi
}

while true ; do
	rps_monitor
	check_xhci
	led_state=$(uci get switch.led_set.enable)
	if [ "$led_state" = "on" ]; then
		fan_led_refresh
		usb_led_refresh
	fi
	sleep 1
done
