#!/usr/bin/env bash

# shellcheck disable=SC1090
source "${XDG_DATA_HOME}/buddy-up/includes/utils.sh"

function get_os () {
    case $(uname -s) in
        Linux*)                 echo linux;;
        Darwin*)                echo darwin-10.12;;
        *) >&2 echo "unsupported os: $(uname -s)"; exit 1;;
    esac
}

APP=gitea
DEST="${XDG_DATA_HOME}/apps/releases/${APP}"
CURRENT="${DEST}/current"
VERSION=${VERSION:-1.15.0}
URL=https://dl.gitea.io/gitea/${VERSION}/gitea-${VERSION}-$(get_os)-$(get_arch).xz

if [ ! -d "${DEST}/${VERSION}" ]; then
    tmp_dir="$(mktemp -d)"
    file=${tmp_dir}/gitea
    curl --silent --retry 5 --location --output "${file}.xz" "${URL}"
    xz --decompress "${file}.xz"
    chmod 755 "${file}"
    mkdir -p "${DEST}/${VERSION}"
    mv "${file}" "${DEST}/${VERSION}/${APP}"

    rm -rf "${tmp_dir}"
fi
set_current_link "${DEST}" "${VERSION}"

unlink_if_set "${XDG_BIN_HOME}/${APP}"
cd "${XDG_BIN_HOME}" || exit 1
ln -s "$(relative_path "${XDG_BIN_HOME}" "${CURRENT}/${APP}")" "${APP}"
cd - &> /dev/null || exit 1