#!/bin/sh

################################################################################
#      This file is part of OpenELEC - http://www.openelec.tv
#      Copyright (C) 2009-2014 Stephan Raue (stephan@openelec.tv)
#
#  OpenELEC is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 2 of the License, or
#  (at your option) any later version.
#
#  OpenELEC is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with OpenELEC.  If not, see <http://www.gnu.org/licenses/>.
################################################################################

# inspired by
# https://github.com/xtranophilist/gnome-shell-extension-cpu-temperature/blob/master/extension.js

TEMP=0

if [ $(basename "$0") = "gputemp" -o "$1" = "gpu" ]; then

  if [ -x /usr/bin/nvidia-smi ]; then
    TEMP="$(/usr/bin/nvidia-smi -q -x | grep '<gpu_temp>' | awk '{ print $1 }' | sed 's,<gpu_temp>,,g')"
  fi

  if [ "$TEMP" = "0" ]; then
    for hwmon in /sys/class/hwmon/*; do
      if [ -f "${hwmon}/name" ]; then
        case $(cat ${hwmon}/name) in
          nouveau|radeon)
            [[ -f "${hwmon}/temp1_input" ]] && TEMP="$(cat ${hwmon}/temp1_input)" && break
            [[ -f "${hwmon}/temp2_input" ]] && TEMP="$(cat ${hwmon}/temp2_input)" && break
            ;;
          coretemp)
            [[ -f "${hwmon}/temp1_input" ]] && TEMP="$(cat ${hwmon}/temp1_input)" && break
            [[ -f "${hwmon}/temp2_input" ]] && TEMP="$(cat ${hwmon}/temp2_input)" && break
            ;;
        esac
      fi
    done

    TEMP="$(( $TEMP / 1000 ))"

  fi
fi

if [ "$1" = "cpu" -o "$TEMP" = "0" ]; then

  for hwmon in /sys/class/hwmon/*; do
    if [ -f "${hwmon}/name" ]; then
      case $(cat ${hwmon}/name) in
        coretemp|k10temp)
          [[ -f "${hwmon}/temp1_input" ]] && TEMP="$(cat ${hwmon}/temp1_input)" && break
          [[ -f "${hwmon}/temp2_input" ]] && TEMP="$(cat ${hwmon}/temp2_input)" && break
          ;;
      esac
    fi
  done

  if [ "$TEMP" = "0" -a -f /sys/class/hwmon/hwmon0/device/temp1_input ]; then
    TEMP="$(cat /sys/class/hwmon/hwmon0/device/temp1_input)"
  fi

  # used on RaspberryPi and amlogic
  if [ "$TEMP" = "0" -a -f /sys/class/thermal/thermal_zone0/temp ]; then
    TEMP="$(cat /sys/class/thermal/thermal_zone0/temp)"
  fi

  TEMP="$(( $TEMP / 1000 ))"
fi

echo "${TEMP} C"
