#!/bin/bash

PORT="$1"
DEVICE="$2"
DURATION="$3"

# Usage: ./examples/plot-bootup <PORT> [DURATION_SECONDS]
# Ports: B1 B2 T1 T2
# Duration: optional, in seconds (default: 120)
# DEVICE: optional, the device to shutdown (default: RPi5)
# NOTE: must be run from the root of the repository

MEASUREMENTS_DIR="/var/lib/rpi-power-hat/measurements"

./examples/shutdown $PORT $DEVICE
sleep 1

echo "Starting current logging for $DURATION seconds"
rpi-power-hat log-current "$PORT" $DURATION -s >/dev/null 2>&1 &
LOGGER_PID=$!

echo "Starting power logging for $DURATION seconds"
rpi-power-hat log-power "$PORT" $DURATION -s >/dev/null 2>&1 &
POWER_LOGGER_PID=$!

sleep 0.5
echo "Powering on $PORT..."
rpi-power-hat set "$PORT" 1

wait "$LOGGER_PID"
wait "$POWER_LOGGER_PID"

CSV_FILE=$(ls -1t "$MEASUREMENTS_DIR"/current_"$PORT"_*.csv 2>/dev/null | head -n 1)
CSV_POWER=$(ls -1t "$MEASUREMENTS_DIR"/power_"$PORT"_*.csv 2>/dev/null | head -n 1)

if ! command -v gnuplot >/dev/null 2>&1; then
echo "gnuplot not found. Install with: sudo apt install gnuplot"
echo "Current CSV: $CSV_FILE"
echo "Power CSV:   $CSV_POWER"
exit 0
fi

OUTPUT_PNG="./examples/bootup_${PORT}.png"

gnuplot <<EOF
set datafile separator comma
set term pngcairo size 1280,720
set output '$OUTPUT_PNG'
set title 'Boot current and power $PORT'
set xlabel 'Time (s)'
set ylabel 'Current (mA)'
set y2label 'Power (mW)'
set y2tics
set tics nomirror
set grid
# The CSV contains: elapsed_time,current_reading (raw ADC)
# Convert raw ADC to mA: current_mA = column(2) / 1.264
# Power CSV contains: elapsed_time,power_reading (likely in microwatts)
# Convert to mW: power_mW = column(2) / 1000
plot \
  '$CSV_FILE' using 1:((column(2))/1.264) axes x1y1 with lines lw 1 lc rgb '#1f77b4' title 'Current', \
#  '$CSV_POWER' using 1:((column(2))/1000.0) axes x1y2 with lines lw 1 lc rgb '#d62728' title 'Power'
EOF

echo "Plot saved: $OUTPUT_PNG"

