#!/usr/bin/env bash
#
# mfboard - Print the MOTHERBOARD from a configuration header, without "BOARD_"
#
#   mfboard [header]            default: Marlin/Configuration.h
#
# Exit status:
#   0  one MOTHERBOARD is active (printed)
#   1  no MOTHERBOARD define
#   2  the active board is ambiguous (all candidates printed)
#
# Some examples choose the board with the preprocessor, e.g. Elegoo's
# Neptune 2:
#
#   #ifndef MOTHERBOARD
#     #ifdef IS_BOARD_1_3
#       #define MOTHERBOARD BOARD_MKS_ROBIN_NANO_V1_3_F4
#     #else
#       #define MOTHERBOARD BOARD_MKS_ROBIN_NANO
#     #endif
#   #endif
#
# Reading every matching line yields both boards, so the env lookup picks
# the wrong one. Conditions are evaluated here instead, following
# #if/#ifdef/#ifndef/#elif/#else the way the compiler does. A condition the
# reader cannot evaluate leaves its branch inactive, so a configuration that
# genuinely cannot be resolved reports every candidate (exit 2) instead of
# silently building the wrong board.
#

MF_BOARD_AWK='
function trim(s) { sub(/^[ \t\r]+/, "", s); sub(/[ \t\r]+$/, "", s); return s }

# Marlin treats a macro as enabled unless it is empty, "0" or "false".
function enabled(n) { return (n in D) && D[n] !~ /^(0|false)$/ }
function numeric(n) { return (n in D) && D[n] ~ /^-?[0-9]+$/ }

# Drop one fully enclosing pair of parentheses.
function unwrap(s,   i, d, c) {
  while (substr(s, 1, 1) == "(" && substr(s, length(s), 1) == ")") {
    d = 0
    for (i = 1; i <= length(s); i++) {
      c = substr(s, i, 1)
      if (c == "(") d++
      else if (c == ")" && --d == 0 && i < length(s)) return s
    }
    if (d != 0) return s
    s = trim(substr(s, 2, length(s) - 2))
  }
  return s
}

# Split on a top-level operator, ignoring parentheses.
function split_top(s, sep, out,   i, c, d, n, cur) {
  n = 0; cur = ""; d = 0
  for (i = 1; i <= length(s); i++) {
    c = substr(s, i, 1)
    if (c == "(") d++
    else if (c == ")" && d > 0) d--
    if (!d && substr(s, i, length(sep)) == sep) { out[++n] = cur; cur = ""; i += length(sep) - 1; continue }
    cur = cur c
  }
  out[++n] = cur
  return n
}

# "1", "0", or "" when the expression cannot be evaluated.
function ev(s,   p, n, i, r, t, id, inner, op, name) {
  s = unwrap(trim(s))
  if (s == "") return "1"

  if ((n = split_top(s, "||", p)) > 1) {
    r = "0"
    for (i = 1; i <= n; i++) { if ((t = ev(p[i])) == "") return ""; if (t != "0") r = "1" }
    return r
  }
  if ((n = split_top(s, "&&", p)) > 1) {
    r = "1"
    for (i = 1; i <= n; i++) { if ((t = ev(p[i])) == "") return ""; if (t == "0") r = "0" }
    return r
  }
  if (substr(s, 1, 1) == "!") { t = ev(substr(s, 2)); return (t == "") ? "" : (t == "0") ? "1" : "0" }

  if (s ~ /^defined[ \t]/) {
    inner = trim(substr(s, 8))
    if (substr(inner, 1, 1) == "(") inner = trim(substr(inner, 2, length(inner) - 2))
    return (inner in D) ? "1" : "0"
  }

  if (match(s, /^(ENABLED|DISABLED|ANY|ALL|NONE)[ \t]*\(/)) {
    name = substr(s, 1, RLENGTH); sub(/[ \t]*\($/, "", name)
    inner = substr(s, RLENGTH + 1)
    sub(/\)[ \t]*$/, "", inner)
    n = split_top(inner, ",", p)
    r = (name == "ALL" || name == "NONE") ? "1" : "0"
    for (i = 1; i <= n; i++) {
      id = trim(p[i]); if (id == "") continue
      t = enabled(id) ? "1" : "0"
      if (name == "ENABLED" || name == "ANY") { if (t != "0") r = "1" }
      else if (name == "ALL") { if (t == "0") r = "0" }
      else if (t != "0") r = "0"   # DISABLED, NONE
    }
    return r
  }

  if (match(s, /(==|!=|>=|<=|>|<)/)) {
    op = substr(s, RSTART, RLENGTH)
    r = trim(substr(s, 1, RSTART - 1))
    t = trim(substr(s, RSTART + RLENGTH))
    if (r ~ /^[A-Za-z_][A-Za-z0-9_]*$/) r = numeric(r) ? D[r] : (enabled(r) ? "1" : "0")
    if (t ~ /^[A-Za-z_][A-Za-z0-9_]*$/) t = numeric(t) ? D[t] : (enabled(t) ? "1" : "0")
    if (r == "" || t == "") return ""
    if (op == "==") return (r + 0 == t + 0) ? "1" : "0"
    if (op == "!=") return (r + 0 != t + 0) ? "1" : "0"
    if (op == ">")  return (r + 0 >  t + 0) ? "1" : "0"
    if (op == "<")  return (r + 0 <  t + 0) ? "1" : "0"
    if (op == ">=") return (r + 0 >= t + 0) ? "1" : "0"
    return (r + 0 <= t + 0) ? "1" : "0"
  }

  if (s ~ /^[A-Za-z_][A-Za-z0-9_]*$/) return enabled(s) ? "1" : "0"
  if (s ~ /^-?[0-9]+$/) return (s + 0 == 0) ? "0" : "1"
  return ""
}

{
  s = trim($0)
  if (s !~ /^#[ \t]*[A-Za-z]/) next
  sub(/^#[ \t]*/, "", s)
  kw = s; sub(/[ \t(].*$/, "", kw)

  if (kw == "if" || kw == "ifdef" || kw == "ifndef") {
    cond = trim(substr(s, length(kw) + 1))
    depth++
    parent[depth] = (depth == 1) ? 1 : active[depth - 1]
    if (kw == "ifdef")       r = (cond in D) ? "1" : "0"
    else if (kw == "ifndef") r = (cond in D) ? "0" : "1"
    else                     r = ev(cond)
    active[depth] = parent[depth] && (r == "1")
    taken[depth] = active[depth]
    next
  }
  if (kw == "elif") {
    if (!depth) next
    if (taken[depth]) { active[depth] = 0; next }
    active[depth] = parent[depth] && (ev(trim(substr(s, 5))) == "1")
    taken[depth] = active[depth]
    next
  }
  if (kw == "else") {
    if (!depth) next
    active[depth] = parent[depth] && !taken[depth]
    taken[depth] = 1
    next
  }
  if (kw == "endif") { if (depth) depth--; next }
  if (kw != "define") next

  body = trim(substr(s, 7))
  if (body == "") next
  n = split(body, w, /[ \t]+/)
  val = trim(substr(body, length(w[1]) + 1))
  sub(/[ \t]*\/\/.*$/, "", val)

  live = 1
  for (i = 1; i <= depth; i++) if (!active[i]) { live = 0; break }

  D[w[1]] = val
  if (w[1] != "MOTHERBOARD") next

  # Remember inactive candidates too, so a config with conditions that cannot
  # be evaluated reports them instead of claiming there is no MOTHERBOARD.
  all[++any] = val
  if (live) c[++seen] = val
}

END {
  if (seen == 1) { print c[1]; exit 0 }
  if (any == 0) exit 1
  if (seen > 1) {
    for (i = 1; i <= seen; i++) printf "%s%s", (i > 1 ? " " : ""), c[i]
    print ""
    exit 2
  }
  # Exactly one candidate is active, but it may depend on a condition that
  # could not be evaluated: report every candidate seen instead of guessing.
  for (i = 1; i <= any; i++) printf "%s%s", (i > 1 ? " " : ""), all[i]
  print ""
  exit 2
}
'

mfboard() {
  local cfg="${1:-Marlin/Configuration.h}" out rc b names=()
  [[ -f $cfg ]] || return 1
  out=$(awk "$MF_BOARD_AWK" "$cfg" 2>/dev/null); rc=$?
  for b in $out; do names+=( "${b#BOARD_}" ); done
  echo "${names[*]}"
  return $rc
}
