#!/bin/bash

LOG_FILE="top_$(date '+%Y%m%d_%H%M%S').log"

echo "Starting MariaDB monitoring..."
echo "Output is being saved to: $LOG_FILE"

# 1. Capture the headers once and add a TIMESTAMP column header at the front
echo "`date \"+%Y-%m-%d %H:%M:%S\"`" > "$LOG_FILE"
echo -e "TIMESTAMP\t$(COLUMNS=500 top -b -n 1 | awk '$1=="PID" && $2=="USER" {print; exit}')" > "$LOG_FILE"

# 2. Stream the data, filter for mariadbd, and prepend the live timestamp
COLUMNS=500 top -b -d 10 | grep -w --line-buffered -E "mariadbd" | awk '{ 
    cmd = "date \"+%Y-%m-%d %H:%M:%S\"";
    cmd | getline dt; 
    close(cmd); 
    print dt "\t" $0; 
    fflush(); 
}' >> "$LOG_FILE" &

# 3. Capture the background Process ID
MONITOR_PID=$!

echo "--------------------------------------------------"
echo "Monitoring is running in the background."
echo "To stop monitoring, run this exact command:"
echo "kill $MONITOR_PID"
echo "--------------------------------------------------"

# Save the kill command to a helper file
echo "kill $MONITOR_PID " > stop-top-monitor.sh
chmod +x stop-top-monitor.sh
