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

START=20
USE_PROCD=1

boot() {
    # procd will call service_triggers
    rc_procd true
}

service_triggers() {
    procd_add_reload_trigger "wan_mac"
}

find_uci_section_i() {
    local key="$2"
    local value="$3"
    local testv
    config_get testv "$1" "$key"
    [[ "$value" = "$testv" ]] && echo "$1"
}

find_uci_section() {
    local config="$1"
    local type="$2"
    local key="$3"
    local value="$4"
    (
        config_load "$config"
        config_foreach find_uci_section_i "$type" "$key" "$value"
    )
}

generate_config() {
    local enabled
    local macaddr
    config_get_bool enabled "config" enabled 0
    config_get macaddr "config" macaddr
    local wan_dev="`uci -q get network.wan.device`"
    [[ -z "$wan_dev" ]] && {
        echo "get network.wan.device failed in uci" >&2
        return 1
    }

    local wan_dev_s=`find_uci_section network device name "$wan_dev" | head -1`
    [[ -z "$wan_dev_s" ]] && {
        uci -q batch <<-EOF >/dev/null
            add network device
            set network.@device[-1].name="$wan_dev"
EOF
        wan_dev_s="@device[-1]"
    }
    if [[ "$enabled" = "1" ]]; then
        uci set "network.$wan_dev_s.macaddr=$macaddr"
    else
        uci delete "network.$wan_dev_s.macaddr"
    fi
    uci commit network
    return 0
}

clean_config() {
    local wan_dev="`uci -q get network.wan.device`"
    [[ -z "$wan_dev" ]] && {
        return 1
    }

    local wan_dev_s=`find_uci_section network device name "$wan_dev" | head -1`
    [[ -z "$wan_dev_s" ]] && {
        return 1
    }
    uci -q batch <<-EOF >/dev/null
        delete network.$wan_dev_s.macaddr
        commit network
EOF
}

start_service() {
    config_load wan_mac
    generate_config && /etc/init.d/network reload
    return 0
}

stop_service() {
    clean_config && /etc/init.d/network reload
}
