#!/bin/sh
# Installs the sailfork CLI: curl -fsSL https://sailfork.com/install | sh
# SAILFORK_VERSION=0.3.0 pins a release; SAILFORK_INSTALL_DIR picks the folder (default ~/.local/bin).
# The version and its SHA-256 come from https://sailfork.com/api/cli/latest (SAILFORK_RELEASE_MANIFEST); archives
# download from https://sailfork.com/sailfork/cli/releases (SAILFORK_DOWNLOAD_BASE).
# Uninstall: curl -fsSL https://sailfork.com/install | sh -s -- --uninstall [--purge]
# (--purge also deletes the saved sign-in and the git credential helper that `sailfork auth setup-git` wrote).
# Windows: irm https://sailfork.com/install.ps1 | iex
set -eu

fail() {
	printf 'sailfork install: %s\n' "$1" >&2
	exit 1
}

is_sailfork() {
	case "$("$1" --version 2>/dev/null </dev/null | head -n 1)" in
	"sailfork "* | "sf "*) return 0 ;;
	esac
	return 1
}

# Atomic: a process starting while this runs sees the old link or the new one, never none.
link_sailfork() {
	rm -f "$dir/.$1.sailfork-new"
	ln -s sailfork "$dir/.$1.sailfork-new" && mv -f "$dir/.$1.sailfork-new" "$dir/$1"
}

# `sf` is also Salesforce's CLI, so one is only touched when it already is sailfork (an old standalone build,
# or a link that no longer works) and is never created.
refresh_short_name() {
	p="$dir/sf"
	if [ -L "$p" ]; then
		case "$(readlink "$p")" in sailfork | "$dir/sailfork") return 0 ;; esac
		[ ! -e "$p" ] || is_sailfork "$p" || {
			printf '\nWarning: %s is not sailfork, so it was left alone.\n' "$p"
			return 0
		}
	elif [ -e "$p" ]; then
		is_sailfork "$p" || {
			printf '\nWarning: %s is not sailfork, so it was left alone.\n' "$p"
			return 0
		}
	else
		return 0
	fi
	link_sailfork sf && printf 'Replaced the old %s with a link to sailfork\n' "$p"
}

uninstall() {
	dir="${SAILFORK_INSTALL_DIR:-$HOME/.local/bin}"
	if [ -n "$purge" ]; then
		[ -x "$dir/sailfork" ] || fail "no sailfork in $dir to purge; set SAILFORK_INSTALL_DIR if it lives elsewhere"
		"$dir/sailfork" uninstall --purge --yes || fail "purge failed; nothing more was removed"
	fi
	removed=0
	for name in git-remote-sailfork sf; do
		p="$dir/$name"
		if [ -L "$p" ]; then
			case "$(readlink "$p")" in
			sailfork | "$dir/sailfork") rm -f "$p" && printf 'Removed %s\n' "$p" && removed=1 ;;
			*) printf 'Left %s: it does not point at sailfork\n' "$p" ;;
			esac
		elif [ -f "$p" ]; then
			if is_sailfork "$p"; then
				rm -f "$p" && printf 'Removed %s\n' "$p" && removed=1
			else
				printf 'Left %s: it is not sailfork\n' "$p"
			fi
		fi
	done
	if [ -f "$dir/sailfork" ]; then
		if is_sailfork "$dir/sailfork"; then
			rm -f "$dir/sailfork" && printf 'Removed %s\n' "$dir/sailfork" && removed=1
		else
			printf 'Left %s: it is not sailfork\n' "$dir/sailfork"
		fi
	fi
	rm -f "$dir/.sailfork.rollback" "$dir/.git-remote-sailfork.sailfork-new" "$dir/.sf.sailfork-new" "$dir/sailfork.new"
	[ "$removed" = 1 ] || printf 'Nothing to uninstall in %s\n' "$dir"
}

main() {
	purge=""
	mode="install"
	for arg in "$@"; do
		case "$arg" in
		--uninstall) mode="uninstall" ;;
		--purge) purge=1 ;;
		*) fail "unknown option $arg; usage: install.sh [--uninstall [--purge]]" ;;
		esac
	done
	if [ "$mode" = "uninstall" ]; then
		uninstall
		return 0
	fi
	[ -z "$purge" ] || fail "--purge goes with --uninstall"

	official="https://sailfork.com/sailfork/cli/releases"
	repo="${SAILFORK_DOWNLOAD_BASE:-$official}"
	dir="${SAILFORK_INSTALL_DIR:-$HOME/.local/bin}"

	case "$(uname -s)" in
	Darwin) os="apple-darwin" ;;
	Linux) os="unknown-linux-musl" ;;
	MINGW* | MSYS* | CYGWIN*) fail "this is a Windows shell; run in PowerShell: irm https://sailfork.com/install.ps1 | iex" ;;
	*) fail "unsupported system $(uname -s); sailfork supports macOS, Linux and Windows" ;;
	esac

	case "$(uname -m)" in
	x86_64 | amd64) arch="x86_64" ;;
	arm64 | aarch64) arch="aarch64" ;;
	*) fail "unsupported CPU $(uname -m); sailfork supports x86_64 and arm64" ;;
	esac

	# A shell running under Rosetta reports x86_64 on Apple silicon; take the native build.
	if [ "$os" = "apple-darwin" ] && [ "$arch" = "x86_64" ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null || echo 0)" = "1" ]; then
		arch="aarch64"
	fi

	if command -v curl >/dev/null 2>&1; then
		fetch_once() { curl -fsSL ${proto:+--proto "$proto" --tlsv1.2} -o "$2" "$1"; }
	elif command -v wget >/dev/null 2>&1; then
		fetch_once() { wget -q ${proto:+--https-only} -O "$2" "$1"; }
	else
		fail "needs curl or wget"
	fi
	# A download can meet an occasional 5xx on its way; one miss should not fail an install.
	fetch() {
		for _ in 1 2 3 4; do
			fetch_once "$1" "$2" && return 0
			sleep 2
		done
		return 1
	}
	proto="=https"
	if [ "$repo" != "$official" ] || [ -n "${SAILFORK_RELEASE_MANIFEST:-}" ]; then
		proto=""
	fi

	if command -v sha256sum >/dev/null 2>&1; then
		sha256() { sha256sum "$1" | cut -d ' ' -f 1; }
	elif command -v shasum >/dev/null 2>&1; then
		sha256() { shasum -a 256 "$1" | cut -d ' ' -f 1; }
	else
		fail "needs sha256sum or shasum to verify the download"
	fi

	tmp="$(mktemp -d)"
	trap 'rm -rf "$tmp"' EXIT INT TERM

	target="$arch-$os"
	asset="sailfork-cli-$target.tar.gz"
	url=""
	expected=""
	version="${SAILFORK_VERSION:-}"
	version="${version#v}"
	# The manifest's hashes are checked against the release signature before sailfork.com serves them, so it vouches
	# for the download; a custom SAILFORK_DOWNLOAD_BASE without a manifest falls back to its own SHA256SUMS.
	manifest="${SAILFORK_RELEASE_MANIFEST:-}"
	[ -n "$manifest" ] || [ "$repo" != "$official" ] || manifest="https://sailfork.com/api/cli/latest"
	if [ -n "$manifest" ]; then
		wanted="$manifest"
		if [ -n "$version" ]; then
			case "$manifest" in *\?*) wanted="$manifest&version=$version" ;; *) wanted="$manifest?version=$version" ;; esac
		fi
		fetch "$wanted" "$tmp/latest.json" 2>/dev/null || fail "could not read the release manifest at $wanted, which vouches for the download; try again in a minute"
		version="$(sed -n 's/.*"version":"\([0-9][0-9.]*\)".*/\1/p' "$tmp/latest.json")"
		entry="$(grep -o "\"$target\":{\"url\":\"[^\"]*\",\"sha256\":\"[0-9a-f]*\"" "$tmp/latest.json" || true)"
		url="$(printf '%s' "$entry" | sed -n 's/.*"url":"\([^"]*\)".*/\1/p')"
		expected="$(printf '%s' "$entry" | sed -n 's/.*"sha256":"\([0-9a-f]*\)".*/\1/p')"
		[ -n "$version" ] && [ -n "$url" ] && [ "${#expected}" = 64 ] || fail "the release manifest at $wanted has no build for $target"
	fi
	[ -n "$version" ] || fail "set SAILFORK_VERSION=<version> or SAILFORK_RELEASE_MANIFEST to install from $repo"
	base="$repo/download/sailfork-cli-v$version"
	[ -n "$url" ] || url="$base/$asset"

	printf 'Downloading sailfork %s for %s\n' "$version" "$target"
	fetch "$url" "$tmp/$asset" || fail "could not download $url"
	if [ -z "$expected" ]; then
		# Releases before 0.3 publish the same list as sha256.sum.
		fetch "$base/SHA256SUMS" "$tmp/SHA256SUMS" 2>/dev/null || fetch "$base/sha256.sum" "$tmp/SHA256SUMS" || fail "could not download the checksums for $asset"
		expected="$(awk -v name="$asset" '$2 == name || $2 == "*" name { print $1; exit }' "$tmp/SHA256SUMS")"
		[ -n "$expected" ] || fail "SHA256SUMS does not list $asset"
	fi
	actual="$(sha256 "$tmp/$asset")"
	[ "$expected" = "$actual" ] || fail "checksum mismatch for $asset (expected $expected, got $actual); nothing was installed"

	tar -xzf "$tmp/$asset" -C "$tmp"
	[ -f "$tmp/sailfork-cli-$target/sailfork" ] || fail "$asset does not contain the sailfork binary"
	mkdir -p "$dir" || fail "cannot create $dir; set SAILFORK_INSTALL_DIR to a folder you can write to"
	mv -f "$tmp/sailfork-cli-$target/sailfork" "$dir/sailfork.new" || fail "cannot write to $dir; set SAILFORK_INSTALL_DIR to a folder you can write to"
	chmod 755 "$dir/sailfork.new"
	mv -f "$dir/sailfork.new" "$dir/sailfork"
	link_sailfork git-remote-sailfork
	refresh_short_name

	printf 'Installed %s to %s\n' "$("$dir/sailfork" --version)" "$dir/sailfork"
	run="sailfork"
	case ":$PATH:" in
	*":$dir:"*) ;;
	*)
		run="$dir/sailfork"
		printf '\n%s is not on your PATH. Add it with:\n' "$dir"
		case "${SHELL:-}" in
		*/fish) printf '  fish_add_path %s\n' "$dir" ;;
		*/zsh) printf "  echo 'export PATH=\"%s:\$PATH\"' >> ~/.zshrc\n" "$dir" ;;
		*) printf "  echo 'export PATH=\"%s:\$PATH\"' >> ~/.bashrc\n" "$dir" ;;
		esac
		printf 'and open a new terminal. Until then, run it as %s.\n' "$run"
		;;
	esac
	shadow="$(command -v sailfork 2>/dev/null || true)"
	if [ -n "$shadow" ] && [ "$shadow" != "$dir/sailfork" ]; then
		run="$dir/sailfork"
		printf '\nWarning: %s comes first on your PATH and shadows the copy just installed. Remove it or put %s first.\n' "$shadow" "$dir"
	fi
	printf '\nNext:\n  %s auth login\n  %s repo clone <owner>/<repo>\nLogin also signs git in, so plain git push and pull work.\nA coding agent can set you up: %s onboard status --json\n' "$run" "$run" "$run"
}

main "$@"
