#!/bin/bash
#
# Copyright (c) Authors: https://www.armbian.com/authors
#
# This file is licensed under the terms of the GNU General Public
# License version 2. This program is licensed "as is" without any
# warranty of any kind, whether express or implied.

# Functions:
#
# show_motd_warning

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
my_name="${0##*/}"
Log=/var/log/armbian-hardware-monitor.log

show_motd_warning() {
cat > /etc/update-motd.d/90-warning <<EOT
#!/bin/bash
echo -e "\e[0;91mAttention:\x1B[0m $1\n"
rm "\$0"
EOT
chmod +x /etc/update-motd.d/90-warning
} # show_motd_warning

get_random_mac ()
{
local prefixes=("02" "06" "0A" "0E")
local random=$(shuf -i 0-3 -n 1)
MACADDR=$(printf ${prefixes[$random]}':%02X:%02X:%02X:%02X:%02X\n' $[RANDOM%256] $[RANDOM%256] $[RANDOM%256] $[RANDOM%256] $[RANDOM%256])
}


# set fixed IP address from first randomly assigned one. If nothing is detected, generate one.
set_fixed_mac ()
{
	if [ -n "$(command -v nmcli)" ]; then
		CONNECTION="$(nmcli -f UUID,ACTIVE,DEVICE,TYPE connection show --active | tail -n1)"
		UUID=$(awk -F" " '/ethernet/ {print $1}' <<< "${CONNECTION}")
		DEVNAME=$(awk -F" " '/ethernet/ {print $3}' <<< "${CONNECTION}")
	else
		DEVNAME=eth0
	fi

	MACADDR=$(/sbin/ip link | grep -A1 ${DEVNAME} | awk -F" " '/ether / {print $2}')

	[[ -z $MACADDR ]] && get_random_mac

	if [[ -n "$(command -v nmcli)" && -n $UUID ]]; then
		nmcli connection modify "$UUID" ethernet.cloned-mac-address "$MACADDR"
		nmcli connection modify "$UUID" -ethernet.mac-address ""
		nmcli connection down "$UUID" >/dev/null 2>&1
		nmcli connection up "$UUID" >/dev/null 2>&1
	elif [[ -f /etc/systemd/network/$DEVNAME.network ]]; then
		if ! grep '^ *MACAddress=' /etc/systemd/network/$DEVNAME.network > /dev/null; then
			sed -i "s/#MACAddress=/MACAddress=$MACADDR/g" /etc/systemd/network/$DEVNAME.network
		fi
	fi
	return 0
} # set fixed mac to the 1st active network adapter
