#!/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 which lspci >/dev/null; then
    if lspci -n | grep 0300 | grep -q 10de; then
      [ -x /usr/bin/nvidia-smi ] && TEMP=`/usr/bin/nvidia-smi -q -x | grep '<gpu_temp>' | awk '{ print $1 }' | sed 's,<gpu_temp>,,g'`
    fi
  fi
fi

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

  # used with coretemp
  for hwmon in hwmon0 hwmon1; do
    for temp in temp1 temp2; do
      if [ "$TEMP" = "0" -a -f /sys/class/hwmon/${hwmon}/${temp}_input ]; then
        if [ -f /sys/class/hwmon/${hwmon}/name ]; then
          if [ ! "$(cat /sys/class/hwmon/${hwmon}/name)" = acpitz ]; then
            TEMP=$(cat /sys/class/hwmon/${hwmon}/${temp}_input)
          fi
        fi
      fi
    done
  done

  # used on AMD systems
  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 ION systems
  if [ "$TEMP" = "0" -a -f /sys/class/hwmon/hwmon0/device/temp2_input ]; then
    TEMP=`cat /sys/class/hwmon/hwmon0/device/temp2_input`
  fi

  # used on some intel systems
  if [ "$TEMP" = "0" -a -f /sys/bus/acpi/devices/LNXTHERM\:00/thermal_zone/temp ]; then
    TEMP=`cat /sys/bus/acpi/devices/LNXTHERM\:00/thermal_zone/temp`
  fi

  # used on some intel systems
  if [ "$TEMP" = "0" -a -f /sys/devices/virtual/thermal/thermal_zone0/temp ]; then
    TEMP=`cat /sys/devices/virtual/thermal/thermal_zone0/temp`
  fi

  # used on RaspberryPi
  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"
