#!/bin/bash

if [ "$EUID" -ne 0 ]; then
    echo "ERROR: Please run as root (sudo)"
    exit 1
fi

mac_set="$(echo $1 | sed 's/://g')"

if [ ! "${#mac_set}" -eq "12" ]; then
    echo "ERROR: Wrong length mac (must be 12 hex characters)"
    exit 1
fi

if ! echo "$mac_set" | grep -qE '^[0-9a-fA-F]{12}$'; then
    echo "ERROR: Invalid hex characters"
    exit 1
fi

WORKDIR="/var/tmp"
TEMP_READ="$WORKDIR/mtd_read.$$.img"

echo "Reading current MTD content..."
if ! dd if=/dev/mtd0 of="$TEMP_READ" bs=1M count=2; then
    echo "ERROR: Failed to read /dev/mtd0"
    exit 1
fi

printf "$(echo "$mac_set" | sed 's/\(..\)/\\x\1/g')" | dd of="$TEMP_READ" bs=1 seek=6 count=6 conv=notrunc

echo "Writing updated image to /dev/mtd0..."
flashcp -v "$TEMP_READ" /dev/mtd0

if [ $? -ne 0 ]; then
    echo "ERROR: flashcp failed"
    rm -f "$TEMP_READ"
    exit 1
fi

NET_IF="end0"
if [ "$mac_set" = "ffffffffffff" ]; then
    echo "MESSAGE: MAC deleted (set to all FF)"
    sed -i "/MACAddress=/d" "/etc/systemd/network/04-$NET_IF.network"
fi

touch /var/rd-auth/.none-registration

rm -f "$TEMP_READ"

echo "MAC write successful. Shutdown? (y/n)"
while : ; do
    read reboot_flag
    if [ "$reboot_flag" = "y" ] || [ "$reboot_flag" = "yes" ] || [ "$reboot_flag" = "n" ] || [ "$reboot_flag" = "no" ]; then
        break
    fi
    echo "MESSAGE: Please enter y, yes, n, or no"
done
if [ "$reboot_flag" = "y" ] || [ "$reboot_flag" = "yes" ]; then
    shutdown -h now
fi

exit 0