#!/bin/bash
# Spoof MAC addresses on network interfaces
# Author: Grozdan "microchip" Nikolov <neutrino8@opensuse.org>
# License: GNU GPLv2+
# Version: 1.0.1

config="/etc/spoofmac/spoofmac.conf"
hwmac="/etc/spoofmac/hwmac"

if [ ! -f "$config" ]; then
	echo "config file '$config' is missing!"
	exit 1
else
	source "$config"
fi

test ! -d "$hwmac" && mkdir -p "$hwmac"

if [ -z "${iface[1]}" ]; then
	echo "iface[1] is not set in config file!"
	exit 1
fi

if [ -z "${spoofmac[1]}" ]; then
	echo "spoofmac[1] is not set in config file!"
	exit 1
fi

# Store current MAC to a file.
# Could be the original or spoofed one
for i in $(seq 1 $iface_max); do
	if [ ! -z "${iface[i]}" ]; then
		ip link show ${iface[i]} | tail -1 | awk '{print $2}' > "$hwmac/hwmac_${iface[i]}"
	fi
done

case "$1" in
	start)
	for i in $(seq 1 $iface_max); do
		if [ ! -z "${iface[i]}" ]; then
			ip link set dev ${iface[i]} down
			ip link set dev ${iface[i]} address ${spoofmac[i]} >/dev/null 2>&1
			ip link set dev ${iface[i]} up
		fi
	done
	echo "You may need to restart your network if you ran spoofmac directly"
	;;
	stop)
	for i in $(seq 1 $iface_max); do
		if [ ! -z "${iface[i]}" ]; then
			if [ -e "$hwmac/hwmac_${iface[i]}" ]; then
				origmac[i]="$(cat "$hwmac/hwmac_${iface[i]}" | head -n 1)"
				ip link set dev ${iface[i]} down
				ip link set dev ${iface[i]} address ${origmac[i]} >/dev/null 2>&1
				ip link set dev ${iface[i]} up
			fi
		fi
	done
	echo "You may need to restart your network if you ran spoofmac directly"
	;;
	*)
	echo "Usage: $(basename $0) {start|stop}"
	exit 1
	;;
esac
