#!/usr/bin/with-contenv bash

function prepend() {
	while read line;
	do echo "${1}${line}";
	done;
}

exec 1> >(prepend "[update-lazystream] ")

echo "checking for update"

current_version=$(lazystream --version)
current_version=v${current_version:11}

echo "installed version: ${current_version}"

latest_release=$(curl -s https://api.github.com/repos/tarkah/lazystream/releases/latest | grep 'musl.tar.gz' | grep browser_download_url | cut -d '"' -f 4)
latest_version=$(echo $latest_release | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+' | head -n 1)

echo "remote version: ${latest_version}"

[ "$(arch)" == "x86_64" ] && release_name=$lazyStreamReleaseName || release_name=$lazyStreamReleaseNameAarch64

if [ $current_version != $latest_version ]; then
    echo "newer version available, downloading..."

    wget https://github.com/tarkah/lazystream/releases/download/$latest_version/lazystream-$latest_version-$release_name.tar.gz -O lazystream.tar.gz; \
    tar xzf lazystream.tar.gz; \
    mv ././lazystream /usr/bin/lazystream; \
    rm lazystream.tar.gz; \
    rm -rf lazystream/; \
    chmod +x /usr/bin/lazystream

    echo "lazystream successfully updated to ${latest_version}"
else
    echo "latest version already installed"
fi