#!/usr/bin/env bash

APP=starship
VERSION=${VERSION:-v0.47.0}
DATA_DIR="${XDG_DATA_HOME}/apps/releases"
DEST_DIR="${DATA_DIR}/${APP}/${VERSION}"

OS=
ARCH=
case $(uname -s) in
    Linux*)     OS=unknown-linux-gnu;;
    Darwin*)    OS=apple-darwin;;
    *)          >&2 echo "unsupported os"; return;
esac

case $(uname -m) in
    x86_64*)    ARCH=x86_64;;
    *)          >&2 echo "unsupported architecture: $(uname -m)"; exit 1;;
esac

URL="https://github.com/starship/starship/releases/download/${VERSION}/starship-${ARCH}-${OS}.tar.gz"
TMP_DIR=
if [[ ! -d "${DEST_DIR}" ]] ; then
    TMP_DIR=$(mktemp --directory)
    TAR_GZ="${TMP_DIR}/release.tar.gz"
    curl --location --silent --output "${TAR_GZ}" "${URL}"
    mkdir -p "${DEST_DIR}"
    tar xzf "${TAR_GZ}" --directory "${DEST_DIR}"
    rm -rf "${TMP_DIR}"
fi

cd "${DATA_DIR}/${APP}" || exit
[[ -s current ]] && unlink current
ln -s "${VERSION}" current

cd "${XDG_BIN_HOME}" || exit
[[ -L "${APP}" ]] || ln --symbolic "${DATA_DIR}/${APP}/current/${APP}" ${APP}