#!/bin/sh

# 1st pib migration for Wifi ac. Up.
migrate_pib_wifiac_1u() (
    
    if [ -f /lib/ar71xx.sh ]; then
        PLATFORM=ar71xx
        . /lib/ar71xx.sh
    elif [ -f /lib/ipq806x.sh ]; then
        PLATFORM=ipq806x
        . /lib/ipq806x.sh
    fi
    board=$(${PLATFORM}_board_name)


    . /lib/functions.sh

    [ -e /lib/firmware/plc/$board/fwconfig ] && . /lib/firmware/plc/$board/fwconfig || exit 1

    USR_PIB=$PLCFW_PATH/user.pib
    NEW_PIB=$PLCFW_PATH/user.pib.tmp
    TMP_PIB=/tmp/user.pib
    eval ORG_PIB="\"$PLCFW_PATH/\${PLCFW_PIB_$(uci_get_state delos baptization MT):-$PLCFW_PIB}\""

    # validate new user PIB and user PIB
    chkpib -q "$NEW_PIB" && mv "$NEW_PIB" "$USR_PIB"
    chkpib -q "$USR_PIB" || {
        rm -f "$USR_PIB"
        exit 0
    }

    # migrate only valid user PIB
    move_data() { # fromfile tofile offset type [size]
        setpib "$2" "$3" "$4" "$(getpib "$1" "$3" "$4" ${5:+"$5"})"
    }

    # transplant old pib into new pib overriding all configs (size of 1.5 PIB format)
    cp "$ORG_PIB" "$TMP_PIB"
    move_data "$USR_PIB" "$TMP_PIB" 0 data 21384

    # copy changed parts from new PIB template
    # prescalers, ttl, customer reserved
    move_data "$ORG_PIB" "$TMP_PIB" 0x1158 data 0x5bc
    move_data "$ORG_PIB" "$TMP_PIB" 0x1714 data 0x5bc
    move_data "$ORG_PIB" "$TMP_PIB" 0x708 long
    move_data "$ORG_PIB" "$TMP_PIB" 0x18c data 0x40

    # mfg string (3.0.0 always used MT2730 PIB)
    move_data "$ORG_PIB" "$TMP_PIB" 0x24 hfid

    mv "$TMP_PIB" "$USR_PIB"
)

# 1st pib migration for Wifi ac. Down.
migrate_pib_wifiac_1d() migrate_pib_wifiac_1u "$@"

#####
# 2nd pib migration for Wifi ac. Up to 2.4.0-01.
migrate_pib_wifiac_2u() (
    . /lib/ar71xx.sh
    board=$(ar71xx_board_name)
    . /lib/functions.sh

    [ -e /lib/firmware/plc/$board/fwconfig ] && . /lib/firmware/plc/$board/fwconfig || exit 1

    USR_PIB=$PLCFW_PATH/user.pib
    NEW_PIB=$PLCFW_PATH/user.pib.tmp
    TMP_PIB=/tmp/user.pib
    eval ORG_PIB="\"$PLCFW_PATH/\${PLCFW_PIB_$(uci_get_state delos baptization MT):-$PLCFW_PIB}\""

    # validate new user PIB and user PIB
    chkpib -q "$NEW_PIB" && mv "$NEW_PIB" "$USR_PIB"
    chkpib -q "$USR_PIB" || {
        rm -f "$USR_PIB"
        exit 0
    }

    # migrate only valid user PIB
    move_data() { # fromfile tofile offset type [size]
        setpib "$2" "$3" "$4" "$(getpib "$1" "$3" "$4" ${5:+"$5"})"
    }

    cp "$USR_PIB" "$TMP_PIB"

    # copy changed parts from new PIB template
    # devolo version, ttl, stability fix
    move_data "$ORG_PIB" "$TMP_PIB" 0x6 byte
    move_data "$ORG_PIB" "$TMP_PIB" 0x708 long
    move_data "$ORG_PIB" "$TMP_PIB" 0x25c8 long

    mv "$TMP_PIB" "$USR_PIB"
)

# 2nd pib migration for Wifi ac. Down.
migrate_pib_wifiac_2d() migrate_pib_wifiac_2u "$@"

########
# 1st pib migration for Wifi n. Up/Down. (same as 2nd ac)
migrate_pib_wifin_1u() migrate_pib_wifiac_2u "$@"
migrate_pib_wifin_1d() migrate_pib_wifiac_2d "$@"
