#!/bin/bash

# === Configuration ===
OUTPUT_FILE="system_usage_log.csv"

# Initialize CSV file with headers if not exists
if [ ! -f "$OUTPUT_FILE" ]; then
  echo "Timestamp,CPU_Usage(%),GPU_Usage(%),RAM_Usage(%),Disk_Usage(%),Alert" > "$OUTPUT_FILE"
fi

# === Functions to gather system metrics ===

get_cpu_usage() {
  mpstat 1 1 | awk '/Average/ && $12 ~ /[0-9.]+/ { print 100 - $12 }'
}

get_gpu_usage() {
  nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -n 1 || echo "0"
}

get_ram_usage() {
  free | awk '/Mem/ { printf("%.2f", $3/$2 * 100.0) }'
}

get_disk_usage() {
  df / | awk 'END {print $5}' | sed 's/%//'
}

send_notification() {
  MESSAGE="$1"
  echo "$(date '+%Y-%m-%d %H:%M:%S') - ALERT: $MESSAGE"
  notify-send "⚠️ System Alert" "$MESSAGE"
}

# === Monitoring loop ===
while true; do
  TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
  CPU_USAGE=$(get_cpu_usage)
  GPU_USAGE=$(get_gpu_usage)
  RAM_USAGE=$(get_ram_usage)
  DISK_USAGE=$(get_disk_usage)

  ALERT="None"

  if (( $(echo "$CPU_USAGE > 70" | bc -l) )); then
    ALERT="CPU usage above 70%"
    send_notification "$ALERT: $CPU_USAGE%"
  elif (( $(echo "$GPU_USAGE > 70" | bc -l) )); then
    ALERT="GPU usage above 70%"
    send_notification "$ALERT: $GPU_USAGE%"
  elif (( $(echo "$RAM_USAGE > 70" | bc -l) )); then
    ALERT="RAM usage above 70%"
    send_notification "$ALERT: $RAM_USAGE%"
  elif (( $(echo "$DISK_USAGE > 70" | bc -l) )); then
    ALERT="Disk usage above 70%"
    send_notification "$ALERT: $DISK_USAGE%"
  fi

  # Log data
  echo "$TIMESTAMP,$CPU_USAGE,$GPU_USAGE,$RAM_USAGE,$DISK_USAGE,$ALERT" >> "$OUTPUT_FILE"

  sleep 300  # Wait 5 minutes
done
