#!/bin/sh

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

function get_wlan_temperature()
{
  add_wlan_temp() {
    local temp="$(wlctl -i "$1" phy_tempsense)"
    [ -n "$temp" ] || temp='-274'

    json_add_object
    json_add_string "name" "wlan-$1"
    json_add_int "temperature" "$temp"
    json_close_object
  }

  config_load wireless
  config_foreach add_wlan_temp wifi-device
}

function get_sfp_temperature()
{
  local temp=""
  local sfp="$(ubus call sfp.ddm get-temperature)"

  json_load "$sfp"
  json_get_var temp temperature

  [ -n "$temp" ] || temp='-274'

  echo "$temp"
}

function get_cpu_temperature()
{
  local cpu="$(cat /sys/devices/virtual/thermal/thermal_zone0/temp 2>/dev/null)"
  [ -n "$cpu" ] || cpu='-274000'

  echo "${cpu:0:-3}"
}

function get_temperature_status()
{
  local hasSfp="$(db -q get hw.board.hasSfp)"

  json_init

  json_add_array "status"

  json_add_object
  json_add_string "name" "cpu"
  json_add_int "temperature" "$(get_cpu_temperature)"
  json_close_object

  [ -s /etc/config/wireless ] && get_wlan_temperature

  [ "$hasSfp" = "1" ] && {
	  json_add_object
	  json_add_string "name" "sfp"
	  json_add_int "temperature" "$(get_sfp_temperature)"
	  json_close_object
  }

  json_close_array

  json_dump
}

function dump_invalid()
{
  json_init
  json_add_string "fault" "invalid request"
  json_dump
}

case "$1" in
    status)
        get_temperature_status
        ;;
    *)
        dump_invalid
        ;;
esac
