#!/usr/bin/env bash
# get-machine-id — Debian replacement for the NixOS helper of the same name.
# evctl and the firmware derive the station serial (EC####) from this.
# Resolution order: mTLS client-cert CN → /etc/iont/machine_id → hostname
# (station-EC#### → EC####) → "unknown".
set -uo pipefail

# 1) cert CN (authoritative once provisioned)
CRT=/data/cert/client/device.crt
if [ -f "$CRT" ] && command -v openssl >/dev/null 2>&1; then
  cn=$(openssl x509 -in "$CRT" -noout -subject 2>/dev/null \
        | sed -n 's/.*CN[[:space:]]*=[[:space:]]*\([^,/]*\).*/\1/p' | tr -d ' ')
  if [ -n "$cn" ]; then echo "$cn"; exit 0; fi
fi

# 2) explicit override file
if [ -f /etc/iont/machine_id ]; then
  id=$(tr -d '\r\n' < /etc/iont/machine_id)
  if [ -n "$id" ]; then echo "$id"; exit 0; fi
fi

# 3) hostname (station-EC1234 → EC1234)
h=$(hostname 2>/dev/null || echo "")
case "$h" in
  station-*) echo "${h#station-}"; exit 0 ;;
  ?*)        echo "$h"; exit 0 ;;
esac

echo "unknown"
