#!/bin/bash

if [ $# -eq 0 ] || [ $# -gt 2 ]; then
    echo "Invalid number of arguments. Please provide at least 1 and at most 2 arguments."
    echo "Usage: $0 [repo] {path}"
    exit 1
fi

if [ $# -eq 1 ]; then
    path=$(pwd)
else
    path=$2
fi

repo=${1#/}
repo=${repo%/}

release=$(curl --silent "https://api.github.com/repos/${repo}/releases/latest" | jq -r .tag_name)
file="${release}.tar.gz"
download="https://github.com/${repo}/archive/refs/tags/${file}"

if [ "$release" == "null" ]; then
    echo "Couldn't fetch latest release. Trying 'main' branch..."

    release=$(curl -s "https://api.github.com/repos/${repo}/commits/main" | grep sha | head -n 1 | cut -d '"' -f 4)
    download="https://github.com/${repo}/archive/refs/heads/main.tar.gz"
    file="${release}.tar.gz"
fi

if [ -f "$path/$file" ]; then
    echo "Release $release already downloaded. Skipping..."
else
    echo "Release not downloaded. Downloading..."
    curl -LJ -o "$path/$file" "$download"
    echo "Download complete."
fi
