#!/bin/bash

# Ausfuehrung im Hintergrund
renice -n 19 $$


. /etc/profile


function CHECK_ONLINE {
  ping -c 1 www.itmastro.de >> /dev/null 2>&1
  o=$?
  if [ $o -ne 0 ]; then
   test -f /tmp/xlinux_monitoring.pid && rm /tmp/xlinux_monitoring.pid
   exit 0
  fi
}
CHECK_ONLINE

SYSTEMID=$(/bin/xlinux-systemid)
test "x$SYSTEMID" == "x" && exit;

function appenddata {
  b=$(echo $2 | /usr/bin/base64 -i -w 0)
  POSTVARS="${POSTVARS}$1=$b&"
}


function SEND_STATIC_DATA {  
  UUID=`dmidecode -t system | grep UUID | cut -d\  -f2`
  UNAME=`/bin/hostname --fqdn`;
  UPTIME=`uptime -s`;
  BASEBOARD1=`dmidecode -s baseboard-manufacturer`
  BASEBOARD2=`dmidecode -s baseboard-product-name`
  CPU=`dmidecode -s processor-version`
  #DISK=$(lsblk -nd | grep "disk" | head -1 | cut -d\  -f1)
  #HDD=`/bin/lsblk -nd --output MODEL,SERIAL /dev/$DISK `
  DISK=$(df / | tail -1 | awk '{print $1}')
  HDD=$(lsblk -ns -o model,serial $DISK | head -1)
  BOOTTIME=$(cat /tmp/xlinux-startup-systemd-end)
  POSTVARS=""
  appenddata "systemid" "$SYSTEMID"
  appenddata "uuid" "$UUID"
  appenddata "mainboard" "$BASEBOARD1 $BASEBOARD2" 
  appenddata "cpu" "$CPU" 
  appenddata "hdd" "$HDD" 
  appenddata "uname" "$UNAME" 
  appenddata "boottime" "$BOOTTIME"
  #/usr/bin/curl --connect-timeout 10 --retry 1 --max-time 10 -X POST -d "$POSTVARS" "https://repository.mastro-it.de/repository-monitoring.php?random=$RANDOM" 2>/dev/null
  echo $POSTVARS > /tmp/xlinux_monitoring.static_sended
}

#sleep $(($RANDOM/2000))


l=$(vmstat -n -w 15 2 2>&1 | tail -1 )
read a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 <<< $l
IOWAIT=$a16
CPULOAD=$(echo "(100-$a15)" | bc)
DISKFREE=$(df -B 1000M --output=avail / | tail -1 | awk '{print $1}')
VERSION=`/bin/cat /etc/debian_version`;
CLIENTIP=`/bin/hostname -I`
CURRENTUSER=$(who | awk '{print $2 " " $1}' | grep -e ^tty  -e ^seat| awk '{print $2}')

POSTVARS=""

if [ ! -f /tmp/xlinux_monitoring.static_sended ]; then
  SEND_STATIC_DATA
fi

appenddata "systemid" "$SYSTEMID"
appenddata "cpuload" "$CPULOAD"
appenddata "iowait" "$IOWAIT"
appenddata "diskfree" "$DISKFREE"
appenddata "version" "$VERSION"
appenddata "clientip" "$CLIENTIP"
appenddata "currentuser" "$CURRENTUSER"

cmd=$(/usr/bin/curl --connect-timeout 10 --retry 1 --max-time 10 -X POST -d "$POSTVARS" "https://repository.mastro-it.de/2022/livedata.php?random=$RANDOM" 2>/dev/null)
if [ "x$cmd" != "x" ]; then
  nohup /bin/xlinux-remotecommand &
fi

