```bash
#!/bin/bash
#
# Ethereum on ARM MOTD Client Status
# Detects EL/CL clients with -mev, testnet variants (hoodi, sepolia)
# and per-network mev-boost services. Handles Erigon integrated CL.
#
# Install: place in /etc/update-motd.d/90-ethereum-clients and chmod +x
# Config: /etc/ethereum-motd.conf (optional)
#

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

DIM="\e[0;90m"
OK="\e[0;92m"
RESET="\x1B[0m"

# --- Base definitions (Defaults) ---
EL_BASES=(geth nethermind besu erigon reth ethrex)
CL_BASES=(lighthouse prysm nimbus teku lodestar grandine)
NETWORKS=(mainnet sepolia hoodi gnosis)

# --- Load User Config (if it exists) ---
CONFIG_FILE="/etc/ethereum-motd.conf"
if [[ -f "$CONFIG_FILE" ]]; then
    # Source the config file, allowing it to override the defaults
    source "$CONFIG_FILE"
fi

# --- systemd check ---
command -v systemctl &>/dev/null || exit 0

# --- Load running units into a fast-lookup map ---
declare -A RUNNING_MAP
for unit in $(systemctl list-units --type=service --state=running --no-legend --plain | awk '{print $1}'); do
    RUNNING_MAP["$unit"]=1
done

strip_service() { echo "${1%.service}"; }

# O(1) check
has_unit() {
    [[ -n "${RUNNING_MAP[$1]}" ]]
}

# --- Detect EL/CL clients ---
detect_clients() {
  local -n BASES=$1
  local type="$2"
  local result=""
  local base net suffix role label

  for base in "${BASES[@]}"; do
    # Networks
    for net in "${NETWORKS[@]}"; do
      # Direct base-network(-mev)
      for suffix in "" "-mev"; do
        local svc="${base}-${net}${suffix}.service"
        if has_unit "$svc"; then
          label="${base}@${net}"
          [[ "$suffix" == "-mev" ]] && label+="-mev"
          result+="$label "
        fi
      done
      # beacon/validator for CL
      if [[ "$type" == "CL" ]]; then
        for role in beacon validator; do
          for suffix in "" "-mev"; do
            local svc="${base}-${role}-${net}${suffix}.service"
            if has_unit "$svc"; then
              label="${base}-${role}@${net}"
              [[ "$suffix" == "-mev" ]] && label+="-mev"
              result+="$label "
            fi
          done
        done
      fi
    done

    # Mainnet (no suffix)
    for suffix in "" "-mev"; do
      local svc="${base}${suffix}.service"
      if has_unit "$svc"; then
        label="${base}"
        [[ "$suffix" == "-mev" ]] && label+="-mev"
        result+="$label "
      fi
      if [[ "$type" == "CL" ]]; then
        for role in beacon validator; do
          local svc2="${base}-${role}${suffix}.service"
          if has_unit "$svc2"; then
            label="${base}-${role}"
            [[ "$suffix" == "-mev" ]] && label+="-mev"
            result+="$label "
          fi
        done
      fi
    done
  done

  echo "$result"
}

active_el_clients="$(detect_clients EL_BASES EL)"
active_cl_clients="$(detect_clients CL_BASES CL)"

# --- mev-boost per-network (Improved Logic) ---
active_mev_boost=""
for net in "${NETWORKS[@]}"; do
    if [[ "$net" == "mainnet" ]]; then
        # Check for mainnet-specific common names
        if has_unit "mev-boost-mainnet.service" || has_unit "mev-boost.service" || has_unit "mevboost.service"; then
            active_mev_boost+="mev-boost@mainnet "
        fi
    else
        # Check for standard testnet name
        if has_unit "mev-boost-${net}.service"; then
            active_mev_boost+="mev-boost@${net} "
        fi
    fi
done

# --- Erigon integrated CL (Improved Logic) ---
# Check if the main detection loop found any erigon client
if [[ "$active_el_clients" == *erigon* ]]; then
    if ! has_unit "erigon-externalcl.service" && [[ -z "$active_cl_clients" ]]; then
        active_cl_clients+="erigon (integrated) "
    fi
fi

# --- Cleanup ---
dedupe() {
  tr ' ' '\n' | sort -u | tr '\n' ' ' | xargs
}
active_el_clients=$(echo "$active_el_clients" | dedupe)
active_cl_clients=$(echo "$active_cl_clients" | dedupe)
active_mev_boost=$(echo "$active_mev_boost" | dedupe)

# --- Output ---
if [[ -n "$active_el_clients" || -n "$active_cl_clients" || -n "$active_mev_boost" ]]; then
  echo ""
  printf "${DIM}Ethereum Clients:${RESET}\n"

  if [[ -n "$active_el_clients" ]]; then
    printf " Execution: ${OK}%s${RESET}\n" "$active_el_clients"
  else
    printf " Execution: ${DIM}None detected${RESET}\n"
  fi

  if [[ -n "$active_cl_clients" ]]; then
    printf " Consensus: ${OK}%s${RESET}\n" "$active_cl_clients"
  else
    printf " Consensus: ${DIM}None detected${RESET}\n"
  fi

  if [[ -n "$active_mev_boost" ]]; then
    printf " MEV-Boost: ${OK}%s${RESET}\n" "$active_mev_boost"
  fi

  echo ""
fi

exit 0