#!/bin/sh

. /lib/functions.sh
. /usr/lib/configsync_lib.sh

CS_SERVICE=cswifi_schedule
SERVICE=wifi_schedule

my_logger() {
    logger -t configsync_executor "${CS_SERVICE}" "${@}"
}

system_to_configsync()
{
    my_logger "This is ${0} system_to_configsync()!"

    config_load ${SERVICE}

    copy_cs_global() {
        local option synced_options='logging forcewifidown recheck_interval modules_retries unload_modules enabled'

        for option in $synced_options; do
            config_get VALUE $1 $option
            uci_cs set ${CS_SERVICE}.global.$option="${VALUE}"
        done
    }
    config_foreach copy_cs_global global

    delete_sections_cs ${CS_SERVICE} entry
    copy_cs_entry() {
        local entry=$(uci_cs add ${CS_SERVICE} entry)
        local option synced_options='daysofweek starttime stoptime enabled'

        for option in $synced_options; do
            config_get VALUE $1 $option
            uci_cs set ${CS_SERVICE}.$entry.$option="${VALUE}"
        done
    }
    config_foreach copy_cs_entry entry

    uci_cs commit ${CS_SERVICE}
    return 0
}

init()
{
    my_logger "This is ${0} init()!"
    if [ ! -d ${CS_CONFIGURATION_PATH} ]; then
        mkdir -p ${CS_CONFIGURATION_PATH}
    fi

    # clear the current CS config to avoid accidental merging
    >${CS_CONFIGURATION_PATH}/${CS_SERVICE}

    uci_cs set ${CS_SERVICE}.configsync=info
    uci_cs set ${CS_SERVICE}.configsync.version=1
    uci_cs set ${CS_SERVICE}.global=global

    system_to_configsync init
}

if [ "${1}" = "init" ] || [ "${1}" = "system_to_configsync" ]; then
    "${@}"
else
    my_logger "Unknown command ${1} in ${0}!"
fi