#/bin/sh

script_path="${0%/*}"
echo "script_path: ${script_path}"

config_file="$script_path/luat_upgrade.ini"

is4GModuleUpgraded=no
ETH0MAC_FILE=luat_eth0mac.cfg
ETH0MAC=`sed -n "s/ethaddr0:\(.*\).*/\1\n/p" /proc/xm/xminfo`
Volume=`cat function.ini | ./busybox grep "volume:" | ./busybox grep -v grep | sed 's/volume://g' | sed 's/\r//g' | sed 's/\n//g' | sed "s/$(echo -e '\015')//g"`

mode=$(awk -F':' '/mode:/ { gsub(/\r|\n/, "", $2); print $2 }' "$config_file")
file=$(awk -F':' '/file:/ { gsub(/\r|\n/, "", $2); print $2 }' "$config_file")
target=$(awk -F':' '/target_revision:/ { gsub(/\r|\n/, "", $2); print $2 }' "$config_file")

if [ -f $script_path/$ETH0MAC_FILE ]; then
    ETH0MAC4FILE=`cat $script_path/$ETH0MAC_FILE | ./busybox grep "eth0mac:" | ./busybox grep -v grep | sed 's/eth0mac://g' | sed 's/\r//g' | sed 's/\n//g' | sed "s/$(echo -e '\015')//g"`
    if [ "$ETH0MAC" = "$ETH0MAC4FILE" ];then
        is4GModuleUpgraded=yes
    fi
fi

echo "ETH0MAC:$ETH0MAC ETH0MAC4FILE:$ETH0MAC4FILE "

if [ "$mode" = "uart" ]; then
    $script_path/uart_upgrade $script_path/$file $target
    if [ $? != 0 ]; then
        echo "uart upgrade failed"
    else
        echo "uart upgrade success"
    fi
fi

if [ "$mode" = "ota" ]; then
    if [ "$is4GModuleUpgraded" = "no" ];then
        ./simple_adec_bind_ao -r 8000 -t g711a -v $Volume -i audio/4GModuleUpdateStart.pcm
        sleep 5
    fi
    $script_path/fota $script_path/$file $target
    if [ $? != 0 ]; then
        echo "ota upgrade failed"
        ./simple_adec_bind_ao -r 8000 -t g711a -v $Volume -i audio/4GModuleUpdateFail.pcm
    else
        echo "ota upgrade success"
        echo "eth0mac:$ETH0MAC" > $script_path/$ETH0MAC_FILE
        sync
        sleep 5
        ./simple_adec_bind_ao -r 8000 -t g711a -v $Volume -i audio/4GModuleUpdateSuc.pcm
    fi

    #OTA升级需要一直播报，提醒升级改设备人员改设备已经升级成功。	
    reboot
fi