#!/bin/sh /etc/rc.common

#----------------------------------------------
#Copyright (C) 2019 Twinzo1 <1282055288@qq.com>
#----------------------------------------------
START=90

interface=$(uci get mac.@mac[0].interface 2>/dev/null)
run_random()
{
	enable=$(uci get mac.@mac[0].enable 2>/dev/null)
	minute=$(uci get mac.@mac[0].minute 2>/dev/null)
	week=$(uci get mac.@mac[0].week 2>/dev/null)
	hour=$(uci get mac.@mac[0].hour 2>/dev/null)

	if [ "$enable"x != "1"x ]; then
		sed -i '/#random_mac/d' /etc/crontabs/root
		killall crond
		/usr/sbin/crond
		return
	fi

	if [ $minute = 0 ] ; then
        	minute="00"
	fi

    	if [ $week = 0 ] ; then
        	week="*"
	fi

	sed -i '/#random_mac/d' /etc/crontabs/root >/dev/null 2>&1
	echo "$minute $hour * * $week /etc/init.d/mac restart #random_mac" >> /etc/crontabs/root
	echo "Auto RANDOM_MAC has started."
	killall crond
	/usr/sbin/crond
}

start() {
	mac=$(uci get mac.@mac[0].macaddr 2>/dev/null)
	wan_network_mac=$(uci get network.$interface.macaddr 2>/dev/null)
	reboot_run=$(uci get mac.@mac[0].reboot_run 2>/dev/null)
	if [ "$reboot_run" != "1" ]; then
		sed -i '/#random_mac/d' /etc/rc.local >/dev/null 2>&1
	else
		sed -i '/#random_mac/d' /etc/rc.local >/dev/null 2>&1
		echo "/etc/init.d/mac restart #random_mac" >> /etc/rc.local
	fi
	
	[ -n "$mac" ] || return 0
	
	if [ "$mac" != "$wan_network_mac" ]; then
		uci set network.$interface.macaddr="$mac" 2>/dev/null
		uci commit 2>/dev/null
		sleep 1
		/etc/init.d/network reload
	fi
	run_random

}
stochastic(){
	echo `dd if=/dev/urandom bs=1 count=32 2>/dev/null | md5sum | cut -b 0-12 | sed 's/\(..\)/\1:/g; s/.$//'`
}

restart()
{	
	local stom=$("stochastic")
	uci set network.$interface.macaddr="$stom" 2>/dev/null
	uci commit 2>/dev/null
	/etc/init.d/network reload

}
