
source /etc/version
BOARD_SN=$(/etc/init.d/boardsn)
BOARD_NAME=$(cat /etc/board)

test -n "${OS_DEBUG}" || source /etc/init.d/os_conf

msg() {
    echo " * $1"
}

msg_begin() {
    echo -n " * $1: "
}

msg_done() {
    test -n "$1" && echo $1 || echo "done"
}

msg_fail() {
    test -n "$1" && echo $1 || echo "failed"
}

msg_background() {
    test -n "$1" && echo $1 || echo "pending"
}

prepare_conf() {
    # $1 - actual config file
    # $2 - system-provided config file
    # $3 - user-provided config file
    
    # long story short:
    #  * user conf file takes precedence, if present
    #  * system conf file is used by default, if actual file absent
    
    actual_conf="$1"
    system_conf="$2"
    user_conf="$3"
    
    if [[ -n "${user_conf}" && -e "${user_conf}" ]]; then
        cp -rf "${user_conf}" "${actual_conf}"
        
        # we want only Unix newlines in conf files
        if [[ -f "${actual_conf}" ]]; then
            sed -i 's/\r//g' "${actual_conf}"
        elif [[ -d "${actual_conf}" ]]; then
            find "${actual_conf}" -type f | xargs -L1 sed -i 's/\r//g'
        fi
        
        grep -E "/boot .*ro[\s,]" /proc/mounts &>/dev/null
        RO=$?
        test ${RO} == 0 && mount -o remount,rw /boot
        rm -rf ${user_conf}
        test ${RO} == 0 && mount -o remount,ro /boot
    fi

    if [[ ! -e "${actual_conf}" && -e "${system_conf}" ]]; then
        mkdir -p $(dirname "${actual_conf}")
        cp -rf "${system_conf}" "${actual_conf}"
    fi
}

select_conf() {
    # $1 - system config file
    # $2 - boot config file
    # $3 - user config file

    # Selects and returns the first existing (and with size > 0) file, in this order:
    #  * user config file
    #  * boot config file
    #  * system config file

    system_conf="$1"
    boot_conf="$2"
    user_conf="$3"
    
    test -s "${user_conf}" && echo "${user_conf}" && return
    test -s "${boot_conf}" && echo "${boot_conf}" && return
    test -s "${system_conf}" && echo "${system_conf}" && return
    
    return 1
}
