#!/bin/bash
# For raspberry we have some extra tests
if [ -x "$(command -v vcgencmd)" ] ; then
TEMP=$(vcgencmd measure_temp | cut -d= -f2 | cut -d\' -f1)
STFLAGS=$(vcgencmd get_throttled |cut -d= -f2)
WAS_UNDERVOLTAGE=$((($STFLAGS & 0x10000)!=0))
IS_UNDERVOLTAGE=$((($STFLAGS & 0x1)!=0))
WAS_THROTTLED=$((($STFLAGS & 0x40000)!=0))
IS_THROTTLED=$((($STFLAGS & 0x4)!=0))
WAS_SOFT_TEMP_ACTIVE=$((($STFLAGS & 0x80000)!=0))
IS_SOFT_TEMP_ACTIVE=$((($STFLAGS & 0x8)!=0))
if [ "$IS_UNDERVOLTAGE" == "1" ] ; then
  echo -e "Undervoltage:\t0\t\tNow\t3\t3\thttps://www.repetier-server.com/knowledgebase/undervoltage-and-throtteling-of-pi/"
elif [ "$WAS_UNDERVOLTAGE" == "1" ] ; then
  echo -e "Undervoltage:\t0\t\tIn past\t2\t3\thttps://www.repetier-server.com/knowledgebase/undervoltage-and-throtteling-of-pi/"
else
  echo -e "Undervoltage:\t0\t\tNever\t1\t1\thttps://www.repetier-server.com/knowledgebase/undervoltage-and-throtteling-of-pi/"
fi

if [ "$IS_THROTTLED" == "1" ] ; then
  echo -e "CPU throttled:\t0\t\tNow\t3\t3\thttps://www.repetier-server.com/knowledgebase/undervoltage-and-throtteling-of-pi/"
elif [ "$WAS_THROTTLED" == "1" ] ; then
  echo -e "CPU throttled:\t0\t\tIn past\t2\t3\thttps://www.repetier-server.com/knowledgebase/undervoltage-and-throtteling-of-pi/"
else
  echo -e "CPU throttled:\t0\t\tNever\t1\t17\thttps://www.repetier-server.com/knowledgebase/undervoltage-and-throtteling-of-pi/"
fi
echo -e "CPU temperature:\t1\t°C\t$TEMP\t1\t2\t"
fi
W=$(w | grep load)
REGEX="load average:[ ]*(.*)"
if [[ $W =~ $REGEX ]] ; then
  LOAD="${BASH_REMATCH[1]}"
  echo -e "CPU load:\t0\t\t$LOAD\t1\t17\t"
fi

FREEMEMORY=$(cat /proc/meminfo | grep MemAvailable | cut -d: -f2 | awk '{$1=$1};1')
FREEMEMORY=$(cat /proc/meminfo | grep MemAvailable | cut -d: -f2 | awk '{$1=$1};1')
if [[ "$FREEMEMORY" == *kB ]] ; then
  FREEMEMORY="$(($(echo "$FREEMEMORY"| cut -d' ' -f1) / 1024)) MB"
fi
echo -e "Free RAM:\t0\t\t$FREEMEMORY\t1\t17\t"

# Disk usage, warn when 90% is used, error if 95% is used
df  -m -l -h --output=avail,pcent,target,source | while read line ; do
  ARRAY=($line)
  DEV=${ARRAY[3]}
  AVAILABLE=${ARRAY[0]}
  USE=${ARRAY[1]}
  USEVAL=${USE%?}
  MOUNT=${ARRAY[2]}
  if [[ "$DEV" == "tmpfs" ]] ; then
	 continue
  fi
  if [[ "$DEV" == "udev" ]] ; then
	 continue
  fi
  if [[ "$AVAILABLE" == "Avail" ]] ; then
	 continue
  fi
  if [[ "$DEV" == "devtmpfs" ]] ; then
	 continue
  fi
  if [[ "$MOUNT" == "/boot" ]] ; then
	 continue
  fi
  if [[ $MOUNT == *"/snap/"* ]]; then
    continue
  fi
  LEVEL=1
  if (( USEVAL >= 90 )) ; then
	  LEVEL=2
  fi
  if (( USEVAL >= 95 )) ; then
	  LEVEL=3
  fi
  echo -e "$MOUNT :\t0\t\tFree ${AVAILABLE}B\t$LEVEL\t14\t"
done
DATE=$(date)
echo -e "Date and time:\t0\t\t${DATE}\t1\t18\t"
REGEX="up (.*)...[0-9]+ user"
if [[ $W =~ $REGEX ]] ; then
  UPTIME="${BASH_REMATCH[1]}"
  echo -e "PC uptime:\t0\t\t${UPTIME}\t1\t18\t"
fi
