#!/usr/bin/bash
#
# powerman/discover.sh — gather USB-DB9 adapter + powerman state on a host
#
# Usage: PROX_HOST=pfv-tsys1 bash tests/remote.sh prox-file powerman/discover.sh
#
set -uo pipefail

echo "============================================"
echo "  PDU / Powerman Discovery"
echo "  Host: $(hostname)"
echo "  Date: $(date)"
echo "============================================"

echo ""
echo "=== 1. USB devices ==="
lsusb 2>/dev/null || echo "(lsusb not available)"

echo ""
echo "=== 2. USB-Serial adapters (ttyUSB*) ==="
ls -la /dev/ttyUSB* 2>/dev/null || echo "(no /dev/ttyUSB* devices)"

echo ""
echo "=== 3. USB-Serial kernel modules ==="
lsmod | grep -iE 'usbserial|ftdi|pl2303|cp210|ch34|cdc_acm' 2>/dev/null || echo "(no relevant modules loaded)"

echo ""
echo "=== 4. dmesg for USB serial (last 30 lines) ==="
dmesg | grep -iE 'ttyUSB|usbserial|ftdi|pl2303|cp210|ch34|converter' | tail -30 2>/dev/null || echo "(no dmesg matches)"

echo ""
echo "=== 5. All serial devices ==="
ls -la /dev/ttyS* /dev/ttyUSB* /dev/ttyACM* 2>/dev/null || echo "(no serial devices found)"

echo ""
echo "=== 6. Powerman installed? ==="
dpkg -l powerman 2>/dev/null || echo "(powerman not installed)"
which powerman 2>/dev/null || echo "(powerman binary not found)"
which powermand 2>/dev/null || echo "(powermand binary not found)"

echo ""
echo "=== 7. Powerman config files ==="
ls -la /etc/powerman/ 2>/dev/null || echo "(no /etc/powerman/ directory)"
ls -la /etc/powerman/*.dev 2>/dev/null || echo "(no .dev files)"
cat /etc/powerman/powerman.conf 2>/dev/null || echo "(no powerman.conf)"

echo ""
echo "=== 8. Available powerman device definitions ==="
ls /usr/share/powerman/*.dev 2>/dev/null || ls /etc/powerman/*.dev 2>/dev/null || echo "(no device definitions found)"

echo ""
echo "=== 9. Powermand service status ==="
systemctl status powerman 2>/dev/null | head -10 || echo "(powerman service not found)"

echo ""
echo "=== 10. Serial port test (quick probe of /dev/ttyUSB0) ==="
if [ -e /dev/ttyUSB0 ]; then
  stty -F /dev/ttyUSB0 2>/dev/null && echo "(port exists and is configurable)" || echo "(port exists but stty failed)"
  # Try to read any pending output
  timeout 2 cat /dev/ttyUSB0 2>/dev/null | head -5 || echo "(no immediate output from port)"
else
  echo "(no /dev/ttyUSB0)"
fi

echo ""
echo "============================================"
echo "  Discovery complete."
echo "============================================"
