#!/bin/sh
# r8s-efs-import: this phone's own modem NV data and Wi-Fi MAC, from its EFS partition (Samsung's, where Android
# keeps them). EFS is never mounted and never written: its node is set read-only first, and debugfs only reads.
#   NV   /nv_data.bin, once: to /root/modem-private/nv_data.bin (0600), the copy s5123-modem boots the modem with
#        and cpd keeps its NV writes in; used only when EFS's nv_data.bin.md5 (MD5 of the data and
#        "Samsung_Android_RIL") vouches for it. Without it the modem unit does not start.
#   MAC  /wifi/.mac.info, every boot: NetworkManager's cloned MAC for the Wi-Fi (in /run: nothing of it is kept)
# Prints neither: one line when one of them is missing, at most.
set -u
EFS=/dev/disk/by-partlabel/efs
[ -b $EFS ] || { echo "no EFS partition" >&2; exit 0; }
blockdev --setro "$(readlink -f $EFS)" 2> /dev/null || true
P=/root/modem-private
if [ ! -s $P/nv_data.bin ]; then
	umask 077
	mkdir -p $P
	N=$P/.nv_data.bin.new
	rm -f $N
	debugfs -R "dump /nv_data.bin $N" $EFS > /dev/null 2>&1
	W=$(debugfs -R "cat /nv_data.bin.md5" $EFS 2> /dev/null | tr -d '\n\r ' | tr A-F a-f)
	H=$( { cat $N 2> /dev/null; printf Samsung_Android_RIL; } | md5sum | cut -c1-32)
	if [ -s $N ] && [ ${#W} = 32 ] && [ "$H" = "$W" ]; then
		mv $N $P/nv_data.bin
	else
		rm -f $N; echo "no modem NV data in EFS that its checksum vouches for: the modem stays off" >&2
	fi
fi
MAC=$(debugfs -R "cat /wifi/.mac.info" $EFS 2> /dev/null | tr -d '\n\r ' | tr A-F a-f)
if echo "$MAC" | grep -Eq '^([0-9a-f]{2}:){5}[0-9a-f]{2}$'; then
	mkdir -p /run/NetworkManager/conf.d
	printf '[connection-r8s-wifi-mac]\nmatch-device=driver:ath11k_pci\nwifi.cloned-mac-address=%s\n' "$MAC" \
		> /run/NetworkManager/conf.d/90-r8s-wifi-mac.conf
else
	echo "no Wi-Fi MAC in EFS: the chip's own" >&2
fi
exit 0
