#!/bin/bash

# Hourly Tracker Script for OpenClaw Workspace
# Created: 2026-03-13
# Purpose: Track CPU, Memory, Disk, and Network Connections

LOG_DIR="/home/amr/.openclaw/workspace/memex/7_system/logs"
LOG_FILE="$LOG_DIR/hourly-stats.log"
DATE=$(date "+%Y-%m-%d %H:%M:%S")

mkdir -p "$LOG_DIR"

log_stats() {
    # 1. CPU
    CPU_LOAD=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
    
    # 2. Memory
    MEM_USAGE=$(free -m | awk 'NR==2{printf "%.2f%%", $3*100/$2 }')
    
    # 3. Load average
    LOAD_AVG=$(uptime | awk -F'load average:' '{ print $2 }' | xargs)
    
    # 4. Disk (/)
    DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}')
    
    # 5. Network connections
    NET_CONNS=$(netstat -an | grep ESTABLISHED | wc -l)
    
    echo "[$DATE] CPU: $CPU_LOAD%, MEM: $MEM_USAGE, LOAD: $LOAD_AVG, DISK: $DISK_USAGE, NET: $NET_CONNS" >> "$LOG_FILE"
}

cleanup_logs() {
    # 6. Auto-cleanup logs older than 30 days
    find "$LOG_DIR" -type f -mtime +30 -delete
}

log_stats
cleanup_logs
