#!/bin/bash

get_latest_version() {
    local base_dir="/usr/bin"
    local versions=$(ls -d ${base_dir}/LoudPlay-streaming-*-Linux 2> /dev/null)

    if [ -z "$versions" ]; then
        echo ""
        return
    fi

    echo "$(echo "$versions" | sort -V | tail -n 1)"
}

get_cfg_path() {
    if [ -f "/etc/LoudPlay/config/client.cfg" ]; then
        echo "/etc/LoudPlay/config/client.cfg"
        return
    fi

    local base_dir=$1
    if [ -f "$base_dir/config/client.cfg" ]; then
        echo "$base_dir/config/client.cfg"
        return
    fi
}

latest_version=$(get_latest_version)

if [ ! -n "$latest_version" ]; then
    echo "No versions of LoudPlay-streaming found."
    exit 1
fi

if [ $# -eq 0 ]; then
    cfg_path=$(get_cfg_path $latest_version)
else
    cfg_path=$1
fi

if [ ! -n "$cfg_path" ]; then
    echo "Failed to find config file. Try to pass it manually"
    exit 1
fi

"$latest_version/bin/streaming" $cfg_path

