#!/bin/sh
#
# HFP-40 workaround (revised due to HFP-297).

set -u

case $(cut -f1 /proc/navico_platform/sub_family_id) in
  1)  # CPU_A
      ACT_STATE="1"
      ;;
  2)  # CPU_B
      ACT_STATE="0"
      ;;
esac

# HFP-732: Temporary workaround - wait up to 90 seconds for klogd to start before slurping /proc/kmsg
TIMEOUT=90
while [ $((TIMEOUT--)) -ge 0 ] && ! pidof klogd >/dev/null; do
  sleep 1
done

while read </proc/kmsg; do
  if echo "$REPLY" | grep -q '[12]-1: USB disconnect'; then
    # Determine which USB port was disconnected (1=Bottom, 2=Top)
    PORT=$(echo "$REPLY" | sed -ne 's/.*\([12]\)-1: USB.*/\1/p')

    # Get the current USB mux configuration (and reformat it into tab-delimited fields).
    # Sample mcu-util output "received get USB1 = 1, USB2 = 1, USB1 currrent OK = 1, USB2 current OK = 1"
    MUX_CFG=$(echo "t 10" | mcu-util | sed '1!d; s/[^=]*= \([0-9]\)/\1\t/g')

    # Determine which CPU the disconnected port is mapped to
    PORT_MAPPING=$(echo "$MUX_CFG" | cut -f "$PORT")

    # echo "USB port $PORT disconnected"
    # echo "MUX configuration: $MUX_CFG"
    # echo "PORT_MAPPING=$PORT_MAPPING ACT_STATE=$ACT_STATE"

    if [ "$PORT_MAPPING" = "$ACT_STATE" ]; then
      # Cycle the port power
      case "$PORT" in
	1) echo "t 36 1 0" | mcu-util ;;
	2) echo "t 36 0 1" | mcu-util ;;
      esac
    fi
  fi
done
