# Scutarius installer: board table lookup. Sourced (not executed) by the
# board-aware installer scripts; installed as /usr/lib/scutarius/sbc-lib
# (patch 0018). Data: /usr/share/scutarius/sbc-boards.
#
# sbc_board: look the running board up. Returns 0 and sets
#   SBC_COMPAT SBC_FIRMWARE SBC_TASK SBC_NFF SBC_REMOVABLE SBC_CONSOLE
# ('-' for none), or returns 1 when the board is not in the table.
SBC_TABLE=${SBC_TABLE:-/usr/share/scutarius/sbc-boards}
SBC_DT=${SBC_DT:-/proc/device-tree}
sbc_board() {
  SBC_COMPAT=
  [ -r "$SBC_DT/compatible" ] || return 1
  SBC_COMPAT=$(tr '\0' '\n' < "$SBC_DT/compatible" | head -1)
  [ -n "$SBC_COMPAT" ] && [ -r "$SBC_TABLE" ] || return 1
  line=$(awk -v c="$SBC_COMPAT" '$1 !~ /^#/ && $1 == c { print; exit }' "$SBC_TABLE")
  [ -n "$line" ] || return 1
  set -- $line
  SBC_FIRMWARE=$2 SBC_TASK=$3 SBC_NFF=$4 SBC_REMOVABLE=$5 SBC_CONSOLE=$6
  return 0
}

# sbc_console_args: the kernel console arguments for a board whose table entry
# says 'dt': the serial port and speed named by the device tree's stdout-path
# (alias form "serialN:BAUD...", as edk2-rk3588 sets it) first, then tty0,
# which becomes /dev/console and so gets interactive prompts. Prints nothing
# when stdout-path is absent or not in that form.
sbc_console_args() {
  [ -r "$SBC_DT/chosen/stdout-path" ] || return 0
  sp=$(tr -d '\0' < "$SBC_DT/chosen/stdout-path")
  case "$sp" in
    serial[0-9]*:[0-9]*)
      n=${sp%%:*}; n=${n#serial}
      baud=$(echo "${sp#*:}" | sed 's/[^0-9].*//')
      echo "console=ttyS$n,$baud console=tty0" ;;
    serial[0-9]*)
      n=${sp#serial}
      echo "console=ttyS$n console=tty0" ;;
  esac
}
