#!/bin/sh

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

board_name=$(board_name)

network_flush_cache

network_find_wan aa

network_get_subnet wansubnet "$aa"

network_get_gateway gwipaddr "$aa"

mem=$(top -n1 | awk -F'[ /tK]+' '$1 ~ /Mem:/{print int($2/($2+$4)*100)}')
cpu1=$(top -n1 | awk -F'[ /t%]+' '$1 ~ /CPU:/{print 100-$8}')
sleep 1
cpu2=$(top -n1 | awk -F'[ /t%]+' '$1 ~ /CPU:/{print 100-$8}')
sleep 2
cpu3=$(top -n1 | awk -F'[ /t%]+' '$1 ~ /CPU:/{print 100-$8}')
avg_cpu=$(awk 'BEGIN{print int(('"$cpu1"'+'"$cpu2"'+'"$cpu3"')/3)}')
if [ "$board_name" == "WOOLINK-MT7621-512M-256M" -o "$board_name" == "WOOLINK-MT7628-128M-32M" ]
then
  dfinfo=$(df -h /overlay | awk '/overlay/{print $5}' | tr -d '%')
else
  dfinfo=$(df -h / | awk '/root/{print $5}' | tr -d '%')
fi
uptime=$(awk -F. '{print $1}' /proc/uptime)
json_init
json_add_string "mem" "$mem"
json_add_string "cpu" "$avg_cpu"
json_add_string "wansubnet" "$wansubnet"
json_add_string "gwipaddr" "$gwipaddr"
json_add_string "disk" "$dfinfo"
json_add_int "uptime" $uptime

if [ -f "/tmp/lbs.txt" ]; then
	latitude=$(cat /tmp/lbs.txt | awk -F ',' '{print $1}')
	longitude=$(cat /tmp/lbs.txt | awk -F ',' '{print $2}')
	if [[ "$latitude" != "" && "$longitude" != "" ]]
	then
		json_add_string "latitude" "$latitude"
		json_add_string "longitude" "$longitude"
	fi
else
	/lib/dyiot/bin/fetch_lbs.sh &
fi

[ -e "/sys/class/thermal/thermal_zone0/temp" ] && {
temp=$(cat /sys/class/thermal/thermal_zone0/temp)
temp=$((temp/1000))
json_add_string "temp" "$temp"
}

json_dump
