#!/bin/bash

cpu_avg() {
    awk -v sleep_time=3 '
    NR==1 {
        idle1=$5
        total1=$2+$3+$4+$5+$6+$7+$8
        next
    }
    NR==2 {
        idle2=$5
        total2=$2+$3+$4+$5+$6+$7+$8
    }
    END {
        idle=idle2-idle1
        total=total2-total1
        usage=(1 - idle/total)*100
        printf("%.2f\n", usage)
    }' \
    <(grep '^cpu ' /proc/stat) \
    <(sleep 3; grep '^cpu ' /proc/stat)
}



while true; do

CPU=$(cpu_avg)
echo "$CPU"
RAM=$(free | awk '/Mem:/ {printf("%.2f\n", $3/$2 * 100)}')

TS=$(date +%s)

temp=$(cat /sys/class/thermal/thermal_zone1/temp)

echo "$TS,$CPU,$RAM,$temp" >> ../status.csv

# 🔥 Cleanup: nur letzte 5 Minuten behalten
CUTOFF=$((TS - 300))

awk -F',' -v cutoff="$CUTOFF" '$1 >= cutoff' ../status.csv > ../status.tmp && mv ../status.tmp ../status.csv

sleep 5
done