#!/bin/sh
# Alkane per-board MAC persistence, with stock-MAC adoption.
#
# Some control boards have no MAC source in hardware (notably the Zynq-7010:
# no eFUSE MAC, no readable device DNA or serial - the PS Serial reads back as
# all zeros). On those boards the mainline macb driver assigns a fresh RANDOM
# MAC on every boot, so the DHCP lease churns or is lost ("IP moves every
# boot"). The bootloader cannot help: the stock U-Boot is RSA-signed and cannot
# save its environment.
#
# Stock firmware had the same lack of a hardware MAC. Its `id2mac` generates a
# random, locally-administered unicast MAC (CRC of a /dev/urandom seed) ONCE and
# caches it in the vendor `configs` partition as /config/mac. So a board that
# ran stock already has a stable MAC on flash; we ADOPT it so the board keeps
# the exact address it used under stock (same ARP/DHCP identity).
#
# Order of preference, applied to eth0 before the network comes up (S09, then
# S10network):
#   1. our own persisted MAC in the `alkane-cfg` MTD (stored as ASCII);
#   2. the stock MAC read raw (no ECC, no UBI attach) from the read-only
#      `stock-cfg` MTD (the vendor `configs` UBI volume), then persisted to
#      alkane-cfg so step 1 wins on every later boot;
#   3. a freshly generated locally-administered unicast MAC, then persisted.
#
# Boards with no `alkane-cfg` partition (every non-Zynq board today) are left
# untouched.

IFACE=eth0
TMP=/tmp/.macaddr
STOCKDUMP=/tmp/.stockcfg

log() { echo "macaddr: $*"; }

mtd_by_label() {
	# Echo /dev/mtdN for the partition labelled $1, or nothing.
	n=$(grep "\"$1\"" /proc/mtd 2>/dev/null | sed 's/:.*//')
	[ -n "$n" ] && echo "/dev/$n"
}

is_unicast() {
	# $1 = aa:bb:cc:dd:ee:ff ; true if a usable unicast MAC (low bit of the
	# first octet clear) and not all-zero / all-ff.
	case "$1" in
	00:00:00:00:00:00|ff:ff:ff:ff:ff:ff|FF:FF:FF:FF:FF:FF) return 1 ;;
	esac
	f=$(echo "$1" | cut -d: -f1)
	[ $(( 0x$f & 1 )) -eq 0 ]
}

read_persisted() {
	# Echo the ASCII MAC stored in $1 (our alkane-cfg), if valid.
	nanddump -q -s 0 -l 32 -f "$TMP" "$1" 2>/dev/null || return 1
	m=$(tr -c '[:print:]' '\n' < "$TMP" 2>/dev/null | grep -oiE '([0-9a-f]{2}:){5}[0-9a-f]{2}' | head -n1)
	[ -n "$m" ] && is_unicast "$m" && echo "$m"
}

read_stock_mac() {
	# Raw-read the stock-cfg partition (no ECC, no UBI attach) and echo the
	# first usable unicast MAC found (stock caches /config/mac as ASCII).
	SDEV=$(mtd_by_label stock-cfg)
	[ -n "$SDEV" ] || return 1
	nanddump -q -n -f "$STOCKDUMP" "$SDEV" 2>/dev/null \
		|| nanddump -q -f "$STOCKDUMP" "$SDEV" 2>/dev/null || return 1
	# Use `strings` (printable runs only) + an anchored whole-line match, so the
	# stock /config/mac file content is isolated and binary UBI noise cannot
	# produce a spurious "xx:xx:.." match (a plain byte-to-line scan does).
	for m in $(strings "$STOCKDUMP" 2>/dev/null | grep -iE '^([0-9a-f]{2}:){5}[0-9a-f]{2}$'); do
		if is_unicast "$m"; then echo "$m"; rm -f "$STOCKDUMP"; return 0; fi
	done
	rm -f "$STOCKDUMP"
	return 1
}

generate_mac() {
	# 6 random bytes rendered as ASCII, first octet forced to locally
	# administered + unicast (set bit1, clear bit0).
	b=$(head -c 6 /dev/urandom 2>/dev/null | od -An -tx1 | tr -s ' ' | sed 's/^ //; s/ *$//; s/ /:/g')
	[ -n "$b" ] || return 1
	f=$(echo "$b" | cut -d: -f1)
	f=$(printf '%02x' $(( (0x$f | 2) & 254 )) )
	echo "$f:$(echo "$b" | cut -d: -f2-)"
}

store_mac() {
	# Persist ASCII MAC $2 to the cfg MTD $1 (erase block 0 first).
	echo "$2" > "$TMP" || return 1
	flash_erase -q "$1" 0 1 >/dev/null 2>&1 || return 1
	nandwrite -p -s 0 "$1" "$TMP" >/dev/null 2>&1 || return 1
	return 0
}

apply_mac() {
	ip link set "$IFACE" down 2>/dev/null
	ip link set "$IFACE" address "$1" 2>/dev/null
	ip link set "$IFACE" up 2>/dev/null
}

case "$1" in
start)
	DEV=$(mtd_by_label alkane-cfg)
	if [ -z "$DEV" ]; then
		# No alkane-cfg partition: nothing to persist (non-Zynq board).
		exit 0
	fi
	printf 'Persisting %s MAC: ' "$IFACE"
	MAC=$(read_persisted "$DEV")
	if [ -n "$MAC" ]; then
		log "restored $MAC from $DEV"
	else
		MAC=$(read_stock_mac)
		if [ -n "$MAC" ]; then
			if store_mac "$DEV" "$MAC"; then
				log "adopted stock MAC $MAC, stored on $DEV"
			else
				log "adopted stock MAC $MAC (persist FAILED)"
			fi
		else
			MAC=$(generate_mac)
			if [ -n "$MAC" ] && store_mac "$DEV" "$MAC"; then
				log "generated+stored $MAC on $DEV"
			else
				echo "FAIL (no MAC)"; exit 0
			fi
		fi
	fi
	apply_mac "$MAC"
	echo "OK ($MAC)"
	;;
stop|restart|reload)
	;;
*)
	echo "usage: $0 {start|stop|restart}"; exit 1 ;;
esac
