#!/bin/sh
#
# Copyright (C) 2018 devolo AG
#

. /usr/lib/lh-migration.sh
. /usr/share/libubox/jshn.sh

LH_PATH="$.SystemConfig.Services.Wireless.Schedule"
UCI_PATH="wifi_schedule"

function add_entry() {
    local entry=$(uci add $UCI_PATH entry)
    if [ -n "$entry" ]; then
        uci_set $UCI_PATH "$entry" daysofweek "$1"
        uci_set $UCI_PATH "$entry" starttime "$2"
        uci_set $UCI_PATH "$entry" stoptime "$3"
        uci_set $UCI_PATH "$entry" enabled '1'
    fi
}

function entry_cb() {
    local Idx="$1"
    local Context="$2"
    
    local On Off
    json_get_var On On
    json_get_var Off Off
    
    add_entry "$Context" "$On" "$Off"
}

function day_cb() {
    local Idx="$1"
    local Context="$2"

    local Day
    json_get_var Day Day

    lh_iterate_array Entry Entries entry_cb "$Day"
}

function migrate_wifi_schedule() {
    logger "Migrating wifi schedule"
    
    config_load $UCI_PATH
    json_init
    json_load "$(lh_filter $LH_PATH)"
    
    local Active WaitForLastStation ForceWifiDown=0
    json_get_var Active Active
    json_get_var WaitForLastStation WaitForLastStation
    uci set $UCI_PATH.@global[0].enabled="$Active"
    [ "$WaitForLastStation" = "0" ] && ForceWifiDown=1
    uci set $UCI_PATH.@global[0].forcewifidown="$ForceWifiDown"
    
    lh_iterate_array Day Days day_cb
    
    uci_commit $UCI_PATH
}

migrate_wifi_schedule