#!/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 10; 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)

echo "$TS,$CPU,$RAM" >> ../status_hour.csv

# 🔥 Cleanup: nur letzte Stunde behalten
CUTOFF=$((TS - 3600))

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

sleep 57
done