#!/bin/bash

# Power cycles target device and then runs a script to collect boottime data
PORT=$1
DEVICE=$2

if [ -z "$PORT" ] || [ -z "$DEVICE" ]; then
    echo "Usage: $0 <PORT> <DEVICE>"
    exit 1
fi

# Restart the device on the port
./examples/shutdown $PORT $DEVICE

echo "Device shutdown, restarting..."
sleep 2
rpi-power-hat set $PORT 1

# Wait for SSH to become available on the device
echo "Waiting for device to come online via SSH..."
for i in {1..120}; do
    if timeout 10 rpi-power-hat ssh $PORT "echo online" &>/dev/null; then
        echo "Device is online!"
        break
    fi
    sleep 1
    echo "ping #$i..."
done

echo "SSH into device"
rpi-power-hat ssh $PORT "bash -s" <<'EOF'
# --- Userspace time calculation ---
KERNEL_DONE_TIME=$(busctl get-property org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager UserspaceTimestampMonotonic | grep -oP '\d+$')

# --- Bootloader time calculation ---

cpuinfo=$(tr -d '\0' < /proc/cpuinfo)
if echo "$cpuinfo" | grep -qi "Pi 5"; then
    timer_address="0x107C003004"
    echo "Pi 5"
elif echo "$cpuinfo" | grep -qi "Pi 4"; then
    timer_address="0xfe003004"
    echo "Pi 4"
elif echo "$cpuinfo" | grep -qi "Pi Zero 2 W"; then
    timer_address="0x3f003004"
    echo "Pi Zero 2 W"
else
    timer_address="0x107C003004"
    echo "Unknown"
fi

timer_freq=1000000   # ticks per secon

# --- Bootloader time calculation continues ---
HEX_VAL=$(sudo busybox devmem "$timer_address" 32)
DEC_VAL=$((HEX_VAL))

UPTIME_US=$(awk '{printf "%0.0f\n", $1 * 1000000}' /proc/uptime)

# scale raw ticks into microseconds
DEC_VAL_US=$(echo "scale=0; ($DEC_VAL * 1000000 / $timer_freq)" | bc)

TIME_IN_BOOTLOADER=$((DEC_VAL_US - UPTIME_US))
BOOTLOADER_TIME=$(echo "scale=2; ($TIME_IN_BOOTLOADER / 1000000)" | bc -l)

# Wait up to 60 seconds for the 'first draw' event to appear in the journal
timeout=60
elapsed=0
while [ $elapsed -lt $timeout ]; do
    if journalctl -b -o short-monotonic --grep "first draw" | grep -q .; then
        break
    fi
    sleep 1
    elapsed=$((elapsed + 1))
done

PANEL_FIRST_DRAW=$(journalctl -b -o short-monotonic --grep "first draw" | grep '^\[' | sed -n '1 p' | awk '{print $2}' | sed 's/.$//')
USERSPACE_TIME=$(echo "scale=2; ($PANEL_FIRST_DRAW - ($KERNEL_DONE_TIME)/1000000)" | bc -l)

# --- Memory information collection ---
MEMINFO=$(cat /proc/meminfo)

echo "Userspace time: $USERSPACE_TIME | Bootloader time: $BOOTLOADER_TIME | Panel first draw time: $PANEL_FIRST_DRAW"
echo "=== MEMINFO START ==="
echo "$MEMINFO"
echo "=== MEMINFO END ==="
EOF