#!/bin/sh
# Installs Anvil (https://anvil.nate.rip):
#
#   curl -fsSL https://anvil.nate.rip/install.sh | sh
#   curl -fsSL https://anvil.nate.rip/install.sh | sh -s -- --uninstall
#
# macOS (Apple silicon): installs Anvil.app as before (/macos/install.sh: /Applications, or ~/Applications), then
# links the `anvil` CLI that the app carries (Contents/Resources/bin/anvil, so it updates with the app) into
# ~/.local/bin, or /usr/local/bin when ~/.local/bin isn't on PATH. --cli-only installs just the CLI, for a Mac
# that only runs a headless node.
#
# Linux (x86_64, arm64): installs ~/.local/bin/anvil and a systemd user unit, anvil-node.service, which runs
# `anvil node serve`, enabled and started, with lingering on so it runs while you're logged out.
#
# Every download is checked against its manifest's size and Ed25519 signature, with Anvil's update key (the
# one in mygo.json), as `anvil update` and the app's updater check them. Running it again updates in place.
# --uninstall removes the binary, the link and the service, and keeps ~/.anvil and the app's settings.
#
# Options: --channel dev (the prerelease feed), --no-service (Linux: no systemd unit), --cli-only (macOS).
# For tests: ANVIL_URL (instead of https://anvil.nate.rip), ANVIL_BIN_DIR (instead of ~/.local/bin),
# ANVIL_INSTALL_DIR and ANVIL_NO_OPEN (passed to the macOS app installer).
set -eu

public_key=nfcyRldNlkXs3WBivlQsbyW55WycUcDTcp+XXpruOrI=
base="${ANVIL_URL:-https://anvil.nate.rip}"
base="${base%/}"
unit=anvil-node.service
channel=stable
action=install
service=1
cli_only=
changed=

usage() {
	cat <<'EOF'
Usage: sh install.sh [--uninstall] [--channel stable|dev] [--no-service] [--cli-only]

Installs Anvil. On macOS, the app and the anvil CLI; on Linux, ~/.local/bin/anvil and the
anvil-node.service systemd user unit. --uninstall removes them and keeps your settings and data.
EOF
}

while [ $# -gt 0 ]; do
	case "$1" in
	--uninstall) action=uninstall ;;
	--channel) [ $# -ge 2 ] || { usage >&2; exit 2; }; channel="$2"; shift ;;
	--channel=*) channel="${1#--channel=}" ;;
	--no-service) service= ;;
	--cli-only) cli_only=1 ;;
	-h | --help) usage; exit 0 ;;
	*) usage >&2; exit 2 ;;
	esac
	shift
done
case "$channel" in
stable) feed="$base/cli" ;;
dev) feed="$base/cli/dev" ;;
*) echo "install.sh: --channel is stable or dev" >&2; exit 2 ;;
esac

fail() {
	echo "install.sh: $*" >&2
	exit 1
}
say() { echo "$*"; }

work=$(mktemp -d 2>/dev/null || mktemp -d -t anvil)
trap 'rm -rf "$work"' EXIT INT TERM

fetch() { # url [file]
	if command -v curl >/dev/null 2>&1; then
		# A dropped connection (curl 56) is retried too, where curl knows --retry-all-errors (7.71+).
		retry="--retry 3"
		curl --help all 2>/dev/null | grep -q -- --retry-all-errors && retry="$retry --retry-all-errors"
		if [ -n "${2:-}" ]; then curl -fsSL $retry -o "$2" "$1"; else curl -fsSL $retry "$1"; fi
	elif command -v wget >/dev/null 2>&1; then
		if [ -n "${2:-}" ]; then wget -qO "$2" "$1"; else wget -qO- "$1"; fi
	else
		fail "needs curl or wget"
	fi
}

os=$(uname -s)
case "$(uname -m)" in
x86_64 | amd64) arch=amd64 ;;
aarch64 | arm64) arch=arm64 ;;
*) fail "no Anvil for $(uname -m) yet: there are builds for x86_64 and arm64" ;;
esac
case "$os" in
Darwin)
	# A shell under Rosetta sees an Intel Mac; the Mac is Apple silicon.
	if [ "$arch" = amd64 ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null)" = 1 ]; then arch=arm64; fi
	target=darwin-$arch
	;;
Linux) target=linux-$arch ;;
*) fail "no Anvil for $os here: on Windows, run  irm $base/install.ps1 | iex  in PowerShell" ;;
esac

if [ -n "${ANVIL_BIN_DIR:-}" ]; then
	bin_dir="$ANVIL_BIN_DIR"
else
	bin_dir="$HOME/.local/bin"
	if [ "$os" = Darwin ]; then
		case ":$PATH:" in
		*":$bin_dir:"*) ;;
		*) [ -d /usr/local/bin ] && [ -w /usr/local/bin ] && bin_dir=/usr/local/bin ;;
		esac
	fi
fi
bin="$bin_dir/anvil"

# json_field prints a top-level string or number field of the manifest in $1. Fields come before the notes,
# and a field name inside the notes is escaped (\"url\"), so the first match is the field.
json_field() {
	sed -n "s/^[[:space:]]*\"$2\":[[:space:]]*\"\{0,1\}\([^\",]*\)\"\{0,1\},\{0,1\}[[:space:]]*\$/\1/p" "$1" | head -n 1
}

# ed25519_verify checks with OpenSSL 3 that the file $3 has the Ed25519 signature $2 (base64) by the public key
# $1 (base64 DER), as MyGo's installer does.
ed25519_verify() {
	printf '%s\n' '-----BEGIN PUBLIC KEY-----' "$1" '-----END PUBLIC KEY-----' >"$work/key.pem"
	printf '%s' "$2" | openssl base64 -d -A >"$work/signature" 2>/dev/null || return 1
	[ "$(wc -c <"$work/signature" | tr -d ' ')" = 64 ] || return 1
	openssl pkeyutl -verify -pubin -inkey "$work/key.pem" -rawin -in "$3" -sigfile "$work/signature" >/dev/null 2>&1
}

# has_ed25519: OpenSSL 1.1.1 and LibreSSL can't check these; test 2 of RFC 8032 tells.
has_ed25519() {
	command -v openssl >/dev/null 2>&1 || return 1
	printf r >"$work/rfc8032"
	ed25519_verify MCowBQYDK2VwAyEAPUAXw+hDiVqStwqnTRt+vJyYLM8uxJaMwM1V8Sr0Zgw= \
		kqAJqfDUyrhyDoILX2QlQKKye1QWUD+Ps3YiI+vbadoIWsHkPhWZbkWPNhPQ8R2MOHsurrQwKu6wDSkWErsMAA== "$work/rfc8032"
}

# verify checks the archive $1 against the signature $2 of its SHA-256 digest: with OpenSSL 3 where there is
# one, else on macOS (LibreSSL) with the curve's arithmetic in JavaScript for Automation, as MyGo's installer.
verify() {
	printf '%s' "$2" | grep -Eq '^[A-Za-z0-9+/]{86}==$' || return 1
	openssl dgst -sha256 -binary <"$1" >"$work/digest" || return 1
	if has_ed25519; then
		ed25519_verify "MCowBQYDK2VwAyEA$public_key" "$2" "$work/digest"
		return
	fi
	[ "$os" = Darwin ] || return 1
	hex() { od -An -v -tx1 | tr -d ' \n'; }
	sig_hex=$(printf '%s' "$2" | base64 -D | hex)
	key_hex=$(printf '%s' "$public_key" | base64 -D | hex)
	k=$({
		printf '%s' "$2" | base64 -D | head -c 32
		printf '%s' "$public_key" | base64 -D
		cat "$work/digest"
	} | shasum -a 512 | cut -c 1-128)
	verifier >"$work/verify.js"
	[ "$(osascript -l JavaScript "$work/verify.js" "$key_hex" "$(echo "$sig_hex" | cut -c 1-64)" "$(echo "$sig_hex" | cut -c 65-128)" "$k" </dev/null 2>/dev/null)" = ok ]
}

# verifier prints the JavaScript that checks an Ed25519 signature (from MyGo's install.sh): its arguments are
# the key, R, S and k in hexadecimal, as little-endian numbers, and it prints ok when [S]B - [k]A encodes as R.
verifier() {
	cat <<'EOF'
function run(argv) {
	var p = 2n ** 255n - 19n
	var l = 2n ** 252n + 27742317777372353535851937790883648493n
	function mod(a) { a %= p; return a < 0n ? a + p : a }
	function pow(b, e) {
		var r = 1n
		for (b = mod(b); e > 0n; e >>= 1n) {
			if (e & 1n) r = r * b % p
			b = b * b % p
		}
		return r
	}
	function inv(a) { return pow(a, p - 2n) }
	var d = mod(-121665n * inv(121666n)), sqrtm1 = pow(2n, (p - 1n) / 4n)
	function num(h) {
		var n = 0n
		for (var i = h.length - 2; i >= 0; i -= 2) n = n << 8n | BigInt(parseInt(h.substr(i, 2), 16))
		return n
	}
	function hex(n) {
		var h = ''
		for (var i = 0; i < 32; i++, n >>= 8n) h += (n & 255n).toString(16).padStart(2, '0')
		return h
	}
	// Points in extended coordinates (X, Y, Z, T), added with the formulas
	// of Hisil, Wong, Carter and Dawson for a = -1.
	function add(a, b) {
		var A = mod((a[1] - a[0]) * (b[1] - b[0])), B = mod((a[1] + a[0]) * (b[1] + b[0]))
		var C = mod(2n * d * a[3] * b[3]), D = mod(2n * a[2] * b[2])
		var E = B - A, F = D - C, G = D + C, H = B + A
		return [mod(E * F), mod(G * H), mod(F * G), mod(E * H)]
	}
	function mul(a, n) {
		var r = [0n, 1n, 1n, 0n]
		for (; n > 0n; n >>= 1n) {
			if (n & 1n) r = add(r, a)
			a = add(a, a)
		}
		return r
	}
	function point(h) {
		if (!/^[0-9a-f]{64}$/.test(h)) return null
		var y = num(h), sign = y >> 255n
		y &= (1n << 255n) - 1n
		if (y >= p) return null
		var u = mod(y * y - 1n), v = mod(d * y * y + 1n)
		var x = pow(u * inv(v), (p + 3n) / 8n)
		if (mod(v * x * x - u) != 0n) {
			x = mod(x * sqrtm1)
			if (mod(v * x * x - u) != 0n) return null
		}
		if (x == 0n && sign == 1n) return null
		if ((x & 1n) != sign) x = p - x
		return [x, y, 1n, mod(x * y)]
	}
	function encode(a) {
		var z = inv(a[2]), x = mod(a[0] * z), y = mod(a[1] * z)
		return hex(y | (x & 1n) << 255n)
	}
	var A = point(argv[0])
	if (!A || !/^[0-9a-f]{64}$/.test(argv[1]) || !/^[0-9a-f]{64}$/.test(argv[2]) || !/^[0-9a-f]{128}$/.test(argv[3])) return 'bad'
	var s = num(argv[2])
	if (s >= l) return 'bad'
	var B = point('5866666666666666666666666666666666666666666666666666666666666666')
	var R = add(mul(B, s), mul([mod(-A[0]), A[1], A[2], mod(-A[3])], num(argv[3]) % l))
	return encode(R) == argv[1] ? 'ok' : 'bad'
}
EOF
}

# install_cli downloads, checks and installs the CLI for $target at $bin.
install_cli() {
	[ "$os" = Darwin ] || has_ed25519 || fail "checking Anvil's signature needs OpenSSL 3.0 or later (the openssl command); install it and run this again"
	manifest_url="$feed/update-$target.json"
	fetch "$manifest_url" "$work/manifest.json" || {
		[ "$target" = darwin-amd64 ] && fail "Anvil isn't released for Intel Macs yet: Apple silicon only for now"
		fail "nothing published for $target on the $channel channel ($manifest_url)"
	}
	version=$(json_field "$work/manifest.json" version)
	url=$(json_field "$work/manifest.json" url)
	size=$(json_field "$work/manifest.json" size)
	signature=$(json_field "$work/manifest.json" signature)
	[ -n "$version" ] && [ -n "$url" ] && [ -n "$size" ] && [ -n "$signature" ] || fail "$manifest_url isn't an update manifest"
	case "$url" in
	https://* | http://*) ;;
	*) url="$feed/$url" ;;
	esac
	if [ -x "$bin" ] && [ ! -L "$bin" ] && "$bin" version 2>/dev/null | grep -q "^anvil $version " &&
		[ -x "$(dirname "$bin_dir")/lib/anvil/herdr-core" ]; then
		say "anvil $version is already installed at $bin."
		return 0
	fi
	say "Downloading anvil $version for ${target}…"
	fetch "$url" "$work/anvil.tar.gz" || fail "could not download $url"
	[ "$(wc -c <"$work/anvil.tar.gz" | tr -d ' ')" = "$size" ] || fail "$url isn't the manifest's $size bytes: not installing it"
	verify "$work/anvil.tar.gz" "$signature" || fail "$url is not signed with Anvil's update key: not installing it"
	mkdir -p "$work/x"
	tar -xzf "$work/anvil.tar.gz" -C "$work/x" || fail "the archive has no anvil binary"
	[ -f "$work/x/anvil" ] || fail "the archive has no anvil binary"
	"$work/x/anvil" version >/dev/null 2>&1 || fail "the downloaded anvil doesn't run here"
	mkdir -p "$bin_dir"
	# Beside the old one and renamed over it, so a running node keeps its file and nothing sees half a binary.
	cp "$work/x/anvil" "$bin_dir/.anvil.new.$$"
	chmod 755 "$bin_dir/.anvil.new.$$"
	rm -f "$bin" 2>/dev/null || true # a link to an app's CLI
	mv -f "$bin_dir/.anvil.new.$$" "$bin" || fail "could not write $bin"
	changed=1
	say "Installed anvil $version at $bin."
	install_hc
}

# herdr-core, which the node runs its terminals and threads in (docs/design/herdr-core.md), goes in
# <prefix>/lib/anvil beside the bin folder: never in bin, where a user's own hc keeps its herdr-core.
install_hc() {
	[ -f "$work/x/herdr-core" ] || return 0
	lib_dir="$(dirname "$bin_dir")/lib/anvil"
	mkdir -p "$lib_dir" || { say "Couldn't make $lib_dir: terminals will end with the node."; return 0; }
	cp "$work/x/herdr-core" "$lib_dir/.herdr-core.new.$$" && chmod 755 "$lib_dir/.herdr-core.new.$$" &&
		mv -f "$lib_dir/.herdr-core.new.$$" "$lib_dir/herdr-core" && say "Installed herdr-core at $lib_dir/herdr-core."
}

path_hint() {
	case ":$PATH:" in
	*":$bin_dir:"*) ;;
	*) say "Add $bin_dir to your PATH:  export PATH=\"$bin_dir:\$PATH\"" ;;
	esac
}

has_systemd_user() {
	command -v systemctl >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1
}

unit_file="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/$unit"

install_service() {
	if ! "$bin" help 2>&1 | grep -q 'node serve'; then
		say "This anvil ($("$bin" version 2>/dev/null)) has no headless node yet, so no service. Run this again once it does."
		return 0
	fi
	if ! has_systemd_user; then
		say "No systemd user session here, so no service: run  $bin node serve  yourself to start the node."
		return 0
	fi
	mkdir -p "$(dirname "$unit_file")"
	# The node starts agents and git, which it finds on the PATH you installed from, plus where anvil is.
	node_path="$bin_dir:$PATH"
	cat >"$work/unit" <<EOF
# Anvil's headless node: anvil node serve, on ~/.anvil/node.sock. Written by $base/install.sh;
# sh install.sh --uninstall removes it.
[Unit]
Description=Anvil node
After=network-online.target

[Service]
ExecStart=$bin node serve
# A node that anvil node connect started first makes this one exit 1 (already running): it retries.
Restart=on-failure
RestartSec=5
Environment=PATH=$node_path

[Install]
WantedBy=default.target
EOF
	if ! cmp -s "$work/unit" "$unit_file" 2>/dev/null; then
		cp "$work/unit" "$unit_file"
		systemctl --user daemon-reload
		changed=1
	fi
	systemctl --user enable "$unit" >/dev/null 2>&1 || fail "could not enable $unit"
	# Restarting stops the node's agents and terminals, so only for a new binary or unit. A node that
	# anvil node connect started outside the unit runs the old binary too: it stops, and the unit takes over.
	if [ -n "$changed" ]; then
		pkill -f "^$bin node serve\$" 2>/dev/null || true
		systemctl --user restart "$unit" || fail "could not start $unit"
	else
		systemctl --user start "$unit" || fail "could not start $unit"
	fi
	if [ "$(loginctl show-user "$(id -un)" -p Linger --value 2>/dev/null || true)" != yes ]; then
		loginctl enable-linger "$(id -un)" 2>/dev/null ||
			say "Couldn't turn on lingering, so the node stops when you log out: sudo loginctl enable-linger $(id -un)"
	fi
	sleep 2
	if systemctl --user is-active --quiet "$unit"; then
		say "Started $unit (systemctl --user status $unit; journalctl --user -u $unit)."
	elif "$bin" node status >/dev/null 2>&1; then
		say "A node started outside $unit is running; the unit takes over when it stops."
	else
		say "$unit didn't stay up. Its log:"
		journalctl --user -u "$unit" -n 15 --no-pager 2>/dev/null || true
		fail "$unit isn't running"
	fi
}

uninstall_linux() {
	if has_systemd_user && [ -f "$unit_file" ]; then
		systemctl --user disable --now "$unit" >/dev/null 2>&1 || true
		rm -f "$unit_file"
		systemctl --user daemon-reload
		say "Removed $unit. Lingering stays as it was (loginctl disable-linger turns it off)."
	fi
	if [ -e "$bin" ] || [ -L "$bin" ]; then
		rm -f "$bin"
		say "Removed $bin."
	fi
	say "Uninstalled anvil. ~/.anvil is still in place."
}

# The app's own installer, from the same site; it checks the app's signature itself.
mac_app() { # [--uninstall]
	fetch "$base/macos/install.sh" "$work/app-install.sh" || fail "could not download $base/macos/install.sh"
	if [ -n "${ANVIL_URL:-}" ]; then
		ANVIL_DOWNLOAD_URL="$base/macos/" sh "$work/app-install.sh" "$@"
	else
		sh "$work/app-install.sh" "$@"
	fi
}

mac_app_path() {
	for dir in ${ANVIL_INSTALL_DIR:-} /Applications "$HOME/Applications"; do
		if [ -x "$dir/Anvil.app/Contents/Resources/bin/anvil" ]; then
			echo "$dir/Anvil.app"
			return 0
		fi
	done
	return 1
}

install_mac() {
	if [ -z "$cli_only" ]; then
		mac_app
		if app=$(mac_app_path); then
			mkdir -p "$bin_dir"
			ln -sfn "$app/Contents/Resources/bin/anvil" "$bin"
			say "Linked $bin to the CLI in $app, which updates with the app."
			path_hint
			return 0
		fi
		say "This version of Anvil.app doesn't carry the CLI yet, so it comes from the CLI feed."
	fi
	install_cli
	path_hint
}

uninstall_mac() {
	if [ -L "$bin" ]; then
		rm -f "$bin"
		say "Removed the link $bin."
	elif [ -e "$bin" ]; then
		rm -f "$bin"
		say "Removed $bin."
	fi
	[ -n "$cli_only" ] || mac_app --uninstall
}

case "$os-$action" in
Darwin-install) install_mac ;;
Darwin-uninstall) uninstall_mac ;;
Linux-install)
	install_cli
	path_hint
	if [ -n "$service" ]; then install_service; fi
	say "Done: anvil version, anvil update, and anvil --help for the rest."
	;;
Linux-uninstall) uninstall_linux ;;
esac
