#!/bin/sh
readonly bootmedia="/dev/block/mmcblk0"

readonly WIFI_BT_FILES_OFFSET=2228224 #2M + 128K

readonly MAGIC="WIFIBT"
readonly WIFI_MIB_FILE_TMP="/tmp/ufmib_taishan.dat"
readonly BT_PSK_FILE_TMP="/tmp/ps-prima2.psr"
readonly MAC_ADDRESS_FILE_TMP="/tmp/mac.txt"

readonly WIFI_MIB_FILE="/etc/firmware/unifi-sdio/ufmib_taishan.dat"
readonly BT_PSK_UPD_FILE="/sdcard/upd/rb/ps-prima2.psr"

readonly LOG_FILE="/sdcard/upd/ps-prima2.log"
readonly RESULT_FILE="/sdcard/upd/rtupdateresult.txt"

read_wifi_bt_files()
{
    echo "Reading Wifi and Bluetooth addresses."

	dd if=$bootmedia of=/tmp/header skip=$WIFI_BT_FILES_OFFSET count=64 bs=1 >> $LOG_FILE
	header="`cat /tmp/header`"
    echo $header >> $LOG_FILE
	if [ "${header:0:6}" != "$MAGIC" ]; then
        echo "Wifi and BT Addresses were never set on this unit." > $LOG_FILE
        echo -1 > $RESULT_FILE
        return 
	fi

    file_num="`echo $header |awk -F ';' '{print $2}'`"
    length1="`echo $header |awk -F ';' '{print $3}'`"
    offset1="`echo $header |awk -F ';' '{print $4}'`"
	length2="`echo $header |awk -F ';' '{print $5}'`"
	offset2="`echo $header |awk -F ';' '{print $6}'`"
	length3="`echo $header |awk -F ';' '{print $7}'`"
	offset3="`echo $header |awk -F ';' '{print $8}'`"

    echo "Reading data from mmcblk">> $LOG_FILE
    dd if=$bootmedia of=$WIFI_MIB_FILE_TMP skip=$offset1 count=$length1 bs=1 >> $LOG_FILE
	dd if=$bootmedia of=$BT_PSK_FILE_TMP skip=$offset2 count=$length2 bs=1 >> $LOG_FILE
	dd if=$bootmedia of=$MAC_ADDRESS_FILE_TMP skip=$offset3 count=$length3 bs=1 >> $LOG_FILE
}

echo "Update ps-prima2.psr file" >> $LOG_FILE
read_wifi_bt_files

addr_item="`awk "END {print}" $BT_PSK_FILE_TMP`"
cp $BT_PSK_UPD_FILE $BT_PSK_FILE_TMP
echo "// PSKEY_BDADDR" >> $BT_PSK_FILE_TMP
echo $addr_item >> $BT_PSK_FILE_TMP

magic="WIFIBT"
file_num="3"
length1="`ls -l $WIFI_MIB_FILE_TMP | awk '{print $5}'`"
length2="`ls -l $BT_PSK_FILE_TMP | awk '{print $5}'`"
length3="`ls -l $MAC_ADDRESS_FILE_TMP | awk '{print $5}'`"
offset1=$(($WIFI_BT_FILES_OFFSET+64))
offset2=$(($offset1+$length1))
offset3=$(($offset2+$length2))
header="$magic;$file_num;$length1;$offset1;$length2;$offset2;$length3;$offset3;"
echo $header >> $LOG_FILE
echo $header > /tmp/header
dd if=/tmp/header of=$bootmedia seek=$WIFI_BT_FILES_OFFSET count=64 bs=1 >> $LOG_FILE

dd if=$WIFI_MIB_FILE_TMP of=$bootmedia seek=$offset1 count=$length1 bs=1 >> $LOG_FILE
dd if=$BT_PSK_FILE_TMP of=$bootmedia seek=$offset2 count=$length2 bs=1 >> $LOG_FILE
dd if=$MAC_ADDRESS_FILE_TMP of=$bootmedia seek=$offset3 count=$length3 bs=1 >> $LOG_FILE

echo 0 > $RESULT_FILE
