#!/bin/sh
# psy installer — downloads the binary for this machine and runs `psy install`,
# which copies it to ~/.local/bin/psy and wires the skills, hooks and status
# line. It writes nothing outside what `psy install` writes, and is safe to
# re-run to upgrade.
#
#   curl -fsSL https://psykit.psycray.com/install.sh | sh
#
# Override the download source with PSY_BASE_URL, or the build with PSY_VERSION.
set -eu

BASE_URL="${PSY_BASE_URL:-https://psykit.psycray.com}"
VERSION="${PSY_VERSION:-latest}"

os=$(uname -s)
case "$os" in
	Darwin) os=darwin ;;
	Linux)  os=linux ;;
	*)
		echo "psy: unsupported OS '$os'." >&2
		echo "    On Windows, run 'irm https://psykit.psycray.com/install.ps1 | iex' in PowerShell (or download psy-windows-amd64.exe / -arm64 and run 'psy.exe install')." >&2
		exit 1
		;;
esac

arch=$(uname -m)
case "$arch" in
	x86_64 | amd64)  arch=amd64 ;;
	arm64 | aarch64) arch=arm64 ;;
	*)
		echo "psy: unsupported architecture '$arch'." >&2
		exit 1
		;;
esac

asset="psy-${os}-${arch}"
url="${BASE_URL}/${VERSION}/${asset}"

tmp=$(mktemp "${TMPDIR:-/tmp}/psy.XXXXXX")
trap 'rm -f "$tmp"' EXIT

echo "psy: downloading ${asset} from ${url}" >&2
if command -v curl >/dev/null 2>&1; then
	# -f fails the pipe on a 404 instead of saving the error page as a binary.
	curl -fsSL "$url" -o "$tmp"
elif command -v wget >/dev/null 2>&1; then
	wget -qO "$tmp" "$url"
else
	echo "psy: need curl or wget to download." >&2
	exit 1
fi

chmod +x "$tmp"

echo "psy: installing" >&2
"$tmp" install

# ~/.local/bin is often not on PATH, so point it out rather than leave a bare
# "psy: command not found".
case ":${PATH}:" in
	*":${HOME}/.local/bin:"*) ;;
	*)
		echo "" >&2
		echo "psy: add ~/.local/bin to your PATH to run 'psy' directly, e.g." >&2
		echo "    echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.zshrc && source ~/.zshrc" >&2
		;;
esac

echo "" >&2
echo "psy: done. Run 'psy doctor' to check the install." >&2
