#!/bin/sh

set -e


# Fix webui passwd
# Version 1.5.x uses passwd.hash
# New webui (2.x.y) uses .passwd 

if [ -f /barix/local/etc/passwd.hash ]; then
    mv /barix/local/etc/passwd.hash /barix/local/etc/.passwd
fi


CONFIG_FILE="/mnt/shadow/config.json"
DEFAULTS_DIR="/barix/config/defaults"

# Factory shadow files can include NUL padding after the JSON document.
webui_default_password=$(tr -d '\000' < "$CONFIG_FILE" |
    jq -er '.applicationPassword | select(type == "string")')

# Factory resets should restore the device password through UCI.
uci -c "$DEFAULTS_DIR" set "icecast.admin.password=$webui_default_password"
uci -c "$DEFAULTS_DIR" commit icecast

current_password=$(uci -q get icecast.admin.password || true)
case "$current_password" in
    ""|icecast_admin_password|barix_icecast)
        uci set "icecast.admin.password=$webui_default_password"
        ;;
esac
uci commit icecast
