#!/bin/bash

PORT=$1
DEVICE=$2

source "/usr/share/rpi-power-hat/scripts/hardware-reader.sh"

shutdown_threshold=$(get_shutdown_threshold "$DEVICE")
timeout_count=0

echo "Shutting down device..."
if rpi-power-hat get "$PORT" | grep -q "OFF"; then
    echo "Device is already off"
    exit 0
elif ! rpi-power-hat ssh "$PORT" "sudo shutdown -h now"; then
    echo "Error: Unable to SSH into device on port $PORT. Cutting power."
    rpi-power-hat set "$PORT" 0
fi

echo "Current hwmon path: $(get_current_hwmon_path "$PORT")"

while true; do
    current_raw=$(cat "$(get_current_hwmon_path "$PORT")" 2>/dev/null || echo "999")
    # If bc fails, fallback to 999
    current_reading=$(echo "scale=3; $current_raw / 1.264" | bc 2>/dev/null | xargs printf "%.0f" 2>/dev/null || echo "999")
    echo "Current reading: ${current_reading} mA (threshold: ${shutdown_threshold} mA)"

    if [[ "$current_reading" -lt "$shutdown_threshold" ]]; then
        echo "Shutdown confirmed - current below threshold"
        break
    fi

    timeout_count=$((timeout_count + 1))
    if [[ $timeout_count -ge 60 ]]; then
        echo "Warning: Shutdown timeout reached, proceeding with power cut"
        break
    fi

    sleep 1
done

sleep 2

rpi-power-hat set "$PORT" 0

echo "Success"






