#!/bin/sh
set -eu

release_url="https://cli.vibebuddy.sh"
install_dir="${VIBE_BUDDY_INSTALL_DIR:-$HOME/.local/bin}"
target="$install_dir/vibebuddy"
alias="$install_dir/buddy"
staged=""

esc="$(printf '\033')"
bold="" brand="" green="" orange="" reset="" red=""
if [ -z "${NO_COLOR:-}" ] && [ "${TERM:-}" != dumb ]; then
	if [ -t 1 ]; then
		bold="${esc}[1m" brand="${esc}[1;38;2;255;155;0m" green="${esc}[32m" orange="${esc}[38;2;255;155;0m" reset="${esc}[0m"
	fi
	if [ -t 2 ]; then
		red="${esc}[31m"
	fi
fi

ok() {
	printf '  %s✓%s %s\n' "$green" "$reset" "$1"
}

fail() {
	printf '  %s✗%s %s\n' "$red" "${red:+${esc}[0m}" "$1" >&2
	exit 1
}

cleanup() {
	rm -rf "$workspace"
	[ -z "$staged" ] || rm -f "$staged"
}

printf '\n  %sVibe Buddy%s\n\n' "$brand" "$reset"

command -v curl >/dev/null 2>&1 || fail "curl is required."

case "$(uname -s):$(uname -m)" in
	Darwin:arm64 | Darwin:aarch64) artifact="vibebuddy-macos-arm64.zip" platform="macOS on Apple silicon" ;;
	Darwin:x86_64 | Darwin:amd64) artifact="vibebuddy-macos-x64.zip" platform="macOS on Intel" ;;
	Linux:x86_64 | Linux:amd64) artifact="vibebuddy-linux-x64" platform="Linux on x64" ;;
	Linux:aarch64 | Linux:arm64) artifact="vibebuddy-linux-arm64" platform="Linux on arm64" ;;
	*) fail "This operating system or CPU isn't supported yet." ;;
esac

workspace="$(mktemp -d)"
trap cleanup 0 HUP INT TERM
manifest="$workspace/latest.json"
binary="$workspace/$artifact"

curl -fsSL "$release_url/latest.json" -o "$manifest" || fail "Couldn't download the release manifest."

field() {
	awk -v artifact="$artifact" -v field="$1" '
		index($0, "\"" artifact "\"") { inside = 1; next }
		inside && /^[[:space:]]*}/ { exit }
		inside && index($0, "\"" field "\"") {
			value = $0
			sub(/^.*:[[:space:]]*/, "", value)
			sub(/,[[:space:]]*$/, "", value)
			sub(/^\"/, "", value)
			sub(/\"$/, "", value)
			print value
			exit
		}
	' "$manifest"
}

version="$(awk '
	index($0, "\"artifacts\"") { exit }
	index($0, "\"version\"") {
		value = $0
		sub(/^.*:[[:space:]]*/, "", value)
		sub(/,[[:space:]]*$/, "", value)
		sub(/^\"/, "", value)
		sub(/\"$/, "", value)
		print value
		exit
	}
' "$manifest")"
path="$(field path)"
size="$(field size)"
expected_sha="$(field sha256)"

printf '%s\n' "$version" | grep -Eq '^[0-9]{4}\.[0-9]+\.[0-9]+\.[0-9]+$' || fail "The release manifest has an invalid version."
case "$path" in
	releases/*/"$artifact") ;;
	*) fail "The release manifest has an invalid download path." ;;
esac
case "$path" in *..* | /*) fail "The release manifest has an unsafe download path." ;; esac
case "$size" in '' | *[!0-9]*) fail "The release manifest has an invalid file size." ;; esac
[ "$size" -gt 0 ] || fail "The release manifest has an invalid file size."
case "$expected_sha" in '' | *[!0-9a-fA-F]*) fail "The release manifest has an invalid checksum." ;; esac
[ "${#expected_sha}" -eq 64 ] || fail "The release manifest has an invalid checksum."
ok "Found $version for $platform"

curl -fsSL "$release_url/$path" -o "$binary" || fail "Couldn't download Vibe Buddy."
actual_size="$(wc -c < "$binary" | tr -d '[:space:]')"
[ "$actual_size" = "$size" ] || fail "The download has the wrong size."

if command -v sha256sum >/dev/null 2>&1; then
	actual_sha="$(sha256sum "$binary" | awk '{ print $1 }')"
elif command -v shasum >/dev/null 2>&1; then
	actual_sha="$(shasum -a 256 "$binary" | awk '{ print $1 }')"
else
	fail "sha256sum or shasum is required."
fi
[ "$actual_sha" = "$expected_sha" ] || fail "The download failed checksum verification."
ok "Downloaded it and checked its SHA-256"

mkdir -p "$install_dir"
install_dir="$(cd "$install_dir" && pwd)"
target="$install_dir/vibebuddy"
alias="$install_dir/buddy"
shown="$install_dir" path_dir="$install_dir"
case "$install_dir" in
	"$HOME"/*) shown="~${install_dir#"$HOME"}" path_dir="\$HOME${install_dir#"$HOME"}" ;;
esac
if [ -e "$alias" ] || [ -L "$alias" ]; then
	[ -L "$alias" ] && [ "$(readlink "$alias")" = vibebuddy ] || fail "buddy already exists in $shown."
fi
# Read the old version before the macOS app bundle or the binary is replaced.
old_version=""
if [ -x "$target" ]; then
	old_version="$("$target" --version 2>/dev/null </dev/null)" || old_version=""
	case "$old_version" in *[!0-9A-Za-z.+-]*) old_version="" ;; esac
fi
staged="$install_dir/.vibebuddy.$$.new"
case "$artifact" in
	*.zip)
		# Check paths and file types before extracting an untrusted archive.
		/usr/bin/unzip -Z1 "$binary" > "$workspace/archive-paths" || fail "Couldn't read the app archive."
		while IFS= read -r entry; do
			case "$entry" in
				'Vibe Buddy.app/' | 'Vibe Buddy.app/Contents/' | 'Vibe Buddy.app/Contents/MacOS/' | 'Vibe Buddy.app/Contents/_CodeSignature/' | 'Vibe Buddy.app/Contents/Resources/' | 'Vibe Buddy.app/Contents/Info.plist' | 'Vibe Buddy.app/Contents/MacOS/vibebuddy' | 'Vibe Buddy.app/Contents/_CodeSignature/CodeResources' | 'Vibe Buddy.app/Contents/CodeResources' | 'Vibe Buddy.app/Contents/Resources/vibebuddy.icns' | 'Vibe Buddy.app/Contents/Resources/Assets.car') ;;
				*) fail "The app archive contains an unexpected path." ;;
			esac
		done < "$workspace/archive-paths"
		/usr/bin/zipinfo -l "$binary" > "$workspace/archive-list"
		awk '$1 ~ /^[bclps]/ {exit 1}' "$workspace/archive-list" || fail "The app archive contains a special file."
		/usr/bin/zipinfo -t "$binary" | awk '$3 > 209715200 {exit 1}' || fail "The app archive is too large."
		/usr/bin/ditto -x -k "$binary" "$workspace/app" || fail "Couldn't extract the app."
		app="$workspace/app/Vibe Buddy.app"
		/usr/bin/codesign --verify --strict -R='anchor apple generic and certificate leaf[subject.OU] = "LM44T82AHX" and identifier "com.byvova.vibe-buddy.cli"' "$app" || fail "The app failed Apple signature verification."
		ok "Checked Apple's Developer ID signature"
		"$app/Contents/MacOS/vibebuddy" install-macos-app "$install_dir" || fail "Couldn't install the app."
		ln -s 'Vibe Buddy.app/Contents/MacOS/vibebuddy' "$staged"
		;;
	*)
		cp "$binary" "$staged"
		chmod 755 "$staged"
		;;
esac
mv -f "$staged" "$target"
staged=""
[ -L "$alias" ] || ln -s vibebuddy "$alias"

if [ -z "$old_version" ]; then
	ok "Installed ${bold}buddy${reset} in $shown"
elif [ "$old_version" = "$version" ]; then
	ok "Reinstalled $version"
else
	ok "Updated $old_version → $version"
fi
# Stop a running background app so the new binary takes over.
"$alias" stop >/dev/null 2>&1 </dev/null || true

case ":$PATH:" in
	*":$install_dir:"*) ;;
	*)
		where="Add this to ~/.profile" line="export PATH=\"$path_dir:\$PATH\""
		case "${SHELL:-}" in
			*/zsh) where="Add this to ~/.zshrc" ;;
			*/bash) where="Add this to ~/.bashrc" ;;
			*/fish) where="Run this" line="fish_add_path \"$path_dir\"" ;;
		esac
		printf "\n  %s!%s %s isn't on your PATH yet. %s:\n    %s%s%s\n" "$orange" "$reset" "$shown" "$where" "$bold" "$line" "$reset"
		;;
esac

if [ -t 1 ] && [ -r /dev/tty ]; then
	printf '\n  Opening Buddy…  Next time, just type %sbuddy%s.\n' "$bold" "$reset"
	"$alias" < /dev/tty
else
	# A reinstall brings back the app it stopped; a first install waits for the person to open it.
	[ -z "$old_version" ] || "$alias" start >/dev/null 2>&1 </dev/null || true
	printf '\n  Type %sbuddy%s to open Buddy.\n' "$bold" "$reset"
fi
