#!/bin/sh

export PATH=$PATH:/usr/bin

CONFIG_VER=$(uci -q get application.main_config.config_ver)

# cleanup leftovers from old update mechanism
rm -f /mnt/data/update_servers.txt

# application.channels_catalog not used since >=6.3.0
uci -q set application.channels_catalog=""

if [ -z "$(uci -q get audioplex.rtp_out)" ]; then
    echo "creating missing section: audioplex.rtp_out"
    uci set audioplex.rtp_out=section
fi

if [ -z "$(uci -q get audioplex.rtp_out.audio_format)" ]; then
    echo "setting missing audioplex.rtp_out.audio_format"
    uci set audioplex.rtp_out.audio_format='PCM16BE'
fi

if [ -z "$(uci -q get application.audio.local_crossfade_ms)" ]; then
    echo "setting missing audio.local_crossfade_ms"
    uci set application.audio.local_crossfade_ms='3000'
fi

if [ -z "$(uci -q get application.main_config.playback_report_enabled)" ]; then
    echo "setting missing playback_report_enabled"
    uci set application.main_config.playback_report_enabled="false"
fi

if [ -z "$(uci -q get application.main_config.flexa_registry_url)" ]; then
    echo "setting missing flexa_registry_url"
    uci set application.main_config.flexa_registry_url='flexa-base.azurewebsites.net'
fi

uci commit

if [ "$CONFIG_VER" -eq "1" ]; then
    echo "migrating V1 configurations to V2.."
        
    # 70% --> 70
    VAL=$(uci -q get network.sonic_ip.volume)
    NEW_VAL=$(echo -n $VAL | cut -d'%' -f 1)
    uci set network.sonic_ip.volume="$NEW_VAL"
        
    VAL=$(uci -q get application.audio.player_volume_percent)
    NEW_VAL=$(echo -n $VAL | cut -d'%' -f 1)
    uci set application.audio.player_volume_percent="$NEW_VAL"
               
    # older units may lack some UCI sections...
    uci set network.wlan0=wlan0
        
    uci set application.main_config.config_ver=2
    uci commit
    echo "rebooting due to migration of configs..."
    reboot &
    sleep 20
    false
else
    true
fi
