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

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

LH_PATH="$.SystemConfig.Services.Wireless.ParentalControl"
UCI_PATH="station_quota"
UCI_PATH_PARENTAL="parental_control"

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" station "$2"
        uci_set $UCI_PATH "$entry" quota "$3"
    fi
}

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

    local Active Mac TimeLimit
    json_get_var Active Active
    json_get_var Mac Mac
    json_get_var TimeLimit TimeLimit

    if [ "$Active" = "1" ] && [ -n "$TimeLimit" ]; then
        add_entry "$Context" "$Mac" "$TimeLimit"
    fi
}

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

    local Day
    json_get_var Day Day

    lh_iterate_array Station Stations station_cb "$Day"
}

function migrate_wifi_parental() {
    logger "Migrating wifi parental control"
    
    config_load $UCI_PATH
    json_init
    json_load "$(lh_filter $LH_PATH)"
    
    local Active
    json_get_var Active Active
    # corporate feature on the WebUI
    uci set $UCI_PATH.@global[0].enabled="$Active"
    uci set $UCI_PATH_PARENTAL.@global[0].enabled="$Active"

    lh_iterate_array Calendar Calendars calendar_cb
    
    uci_commit $UCI_PATH
    uci_commit $UCI_PATH_PARENTAL
}

migrate_wifi_parental
