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

. /usr/lib/lh-migration.sh

function migrate_plc() {
    logger "Migrating PLC"
    local lh_path="$.SystemConfig.Services"
    local uci_path="plc"

    # migrate compatibility settings / notches
    
    local lh_config="$(lh_filter $lh_path.HomePlug.ActiveNotchSet)"

    local compat_mode
    local user_notches
    
    case "$lh_config" in
        1)
            compat_mode=""
            user_notches="2850-3155,3400-3500,3800-3950,4650-4850,5450-5730,6150-6160,6525-6765,8815-9040,9545-9555,10005-10100,11175-11400,11665-11675,13200-13360,13865-13875,15010-15100,15445-15455,17900-18030,21924-22000,23200-23350"
            ;;
        2)
            compat_mode=""
            user_notches="3850-4000,5800-6300,7100-7600,9300-10000,11500-12100,13500-13900,15000-15800,17400-17900,18900-19100,21400-21900,25600-26100,26500-29700"
            ;;
        3)
            compat_mode=""
            user_notches="26960-27410"
            ;;
        4)
            compat_mode=""
            user_notches="26560-27410"
            ;;
        5)
            compat_mode=""
            user_notches="14453-14453,17956-17956,20898-20898,24780-24780,26123-27905,50000-52000"
            ;;
        6)
            compat_mode=""
            user_notches="6127-6176,9521-9570,11645-11694,13842-13818,15429-15478"
            ;;
        7)
            compat_mode=""
            user_notches="5900-6200,7200-7450"
            ;;
        8)
            compat_mode=siso_full
            user_notches=""
            ;;
        9)
            compat_mode=mimo_vdsl35b
            user_notches=""
            ;;
        *)
            compat_mode=""
            user_notches=""
            ;;
    esac        

    logger "Using compat mode: '$compat_mode'"
    logger "Using user notches: '$user_notches'"
    uci set $uci_path.plc.compat_mode="$compat_mode"
    uci set $uci_path.plc.user_notches="$user_notches"

    # migrate NMK
    
    local nmk_cfg="$(lh_filter $lh_path.HomePlug.Config.NMK)"
    local nmk_bap="$(lh_filter $lh_path.System.Baptization.DlanFactoryNmk)"
    
    local nmk
    if [ -n "$nmk_cfg" ]; then
        nmk="$nmk_cfg"
    elif [ -n "$nmk_bap" ]; then
        nmk="$nmk_bap"
    else
        nmk="HomePlugAV"
    fi

    # We cannot modify the PIB file here since it does not yet exist. Write it to /tmp
    # so the PLC init script can use it.
    logger "Using NMK: $nmk"
    echo "LH_NMK=$nmk" > /tmp/lh_nmk
    
    uci commit $uci_path
}

migrate_plc
