#!/usr/bin/env bash

set -euo pipefail

XDG_BIN_HOME=${XDG_BIN_HOME:-${HOME}/.local/bin}
XDG_DATA_HOME=${XDG_DATA_HOME:-${HOME}/.local/share}
XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-${HOME}/.config}

SCRIPTS_DIR=$(dirname "$0")
REPO_DIR=${SCRIPTS_DIR}/..
INCLUDES_DIR=${REPO_DIR}/dot_local/share/buddy-up/includes

# shellcheck disable=SC1091
source "${INCLUDES_DIR}/utils.sh"

APP=chezmoi
VERSION=${VERSION:-2.52.1}
DEST=${XDG_DATA_HOME}/apps/releases/${APP}

main() (
	URL=https://github.com/twpayne/chezmoi/releases/download/v${VERSION}/chezmoi_${VERSION}_$(get_os)_$(get_arch).tar.gz

	extract_tarball "${URL}" "${DEST}/${VERSION}"
	set_current_link "${DEST}" "${VERSION}"
	set_link "${XDG_BIN_HOME}/${APP}" "${DEST}" "${APP}"
	set_link "${XDG_CONFIG_HOME}/bash/bashrc.d/chezmoi.sh" "${DEST}" "completions/chezmoi-completion.bash"
	set_link "${XDG_CONFIG_HOME}/zsh/zshrc.d/chezmoi.zsh" "${DEST}" "completions/chezmoi.zsh"
	set_link "${XDG_CONFIG_HOME}/fish/completions/chezmoi.fish" "${DEST}" "completions/chezmoi.fish"
)

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

main "${@}"