#!/bin/sh /etc/rc.common
#
# Copyright (C) 2015 OpenWrt-dist
# Copyright (C) 2016 fw867 <ffkykzs@gmail.com>
#
# This is free software, licensed under the GNU General Public License v3.
# See /LICENSE for more information.
#

START=99

CONFIG=timewol

uci_get_by_type() {
	local index=0
	if [ -n $4 ]; then
		index=$4
	fi
	local ret=$(uci get $CONFIG.@$1[$index].$2 2>/dev/null)
	echo ${ret:=$3}
}

is_true() {
	case $1 in
		1|on|true|yes|enabled) echo 0;;
		*) echo 1;;
	esac
}

load_config() {
	ENABLED=$(uci_get_by_type basic enable)
	return $(is_true $ENABLED)
}

add_rule(){
sed -i '/etherwake/d' /etc/crontabs/root >/dev/null 2>&1
for i in $(seq 0 100)
	do
		local macaddr=$(uci_get_by_type macclient macaddr '' $i)
		local maceth=$(uci_get_by_type macclient maceth '' $i)
		local minute=$(uci_get_by_type macclient minute '' $i)
		local hour=$(uci_get_by_type macclient hour '' $i)
		local day=$(uci_get_by_type macclient day '' $i)
		local month=$(uci_get_by_type macclient month '' $i)
		local weeks=$(uci_get_by_type macclient weeks '' $i)
		if [ -z $macaddr ] || [ -z $maceth ]; then
			break
		fi
		if [ -z $minute ] ; then
        minute="0"
		fi
		if [ -z $hour ] ; then
        hour="*"
		fi
		if [ -z $day ] ; then
        day="*"
		fi
		if [ -z $month ] ; then
        month="*"
		fi
		if [ -z $weeks ] ; then
        weeks="*"
		fi
   echo "$minute $hour $day $month $weeks /usr/bin/etherwake -D -i $maceth $macaddr" >> /etc/crontabs/root
done
}

start() {
    ! load_config && exit 0
    add_rule
}
stop() {
	sed -i '/etherwake/d' /etc/crontabs/root >/dev/null 2>&1
}
