#!/bin/sh
# Kapable MoneyWorks office agent installer for macOS (PLAT-2180, design v4.2 D34, D43).
#
#   curl -fsSL https://releases.kapable.ai/<installer path> | KAPABLE_MW_ORG=<org> KAPABLE_MW_CODE=mwe_... sh
#
# Checks the code and org, downloads burrow-agent and checks its SHA-256 against
# the pinned value, makes ~/.kapable-mw-agent/<org> (0700), runs
# `burrow-agent moneyworks-enrol` (which checks the connector's signed answer),
# then installs and starts the LaunchAgent ai.kapable.mw-agent-<org>.
# The pins below are filled by render.sh at publish time.
set -eu
umask 077

AGENT_URL_DARWIN_ARM64='https://releases.kapable.ai/v1/artifacts/a9ae11f2a049f4b2e065e26c0e3b7d5c362d612c3ae97f362c9e02fab3680ceb'
AGENT_SHA256_DARWIN_ARM64='a9ae11f2a049f4b2e065e26c0e3b7d5c362d612c3ae97f362c9e02fab3680ceb'
AGENT_URL_DARWIN_X86_64='https://releases.kapable.ai/v1/artifacts/d78fc7406aaa06d7e0bf7b96eb23bd643c3e032ec27e6eea15b1be3a3ff680df'
AGENT_SHA256_DARWIN_X86_64='d78fc7406aaa06d7e0bf7b96eb23bd643c3e032ec27e6eea15b1be3a3ff680df'
CONNECTOR_KEY='c1=RSJ8/oYHIzZdZXdlLxsFT6vBb+4OsMROMZ/AzVGdqwE='
ENROL_URL_TEMPLATE='https://<org>.kapable.ai/moneyworks-connection/agent/enrol'
UNINSTALL_URL='https://releases.kapable.ai/v1/artifacts/1f4515f833e51ae968aa0f109f09790035303683fbb77aef6c313adcd6ea5086'

TMP_DIR=''
cleanup() {
	if [ -n "$TMP_DIR" ]; then
		rm -rf "$TMP_DIR"
	fi
}
trap cleanup EXIT
trap 'exit 130' INT TERM

# fail <human line> [details] [exit code]
fail() {
	printf '%s\n' "$1" >&2
	if [ -n "${2:-}" ]; then
		printf 'Details: %s\n' "$2" >&2
	fi
	exit "${3:-1}"
}

# 1. Shapes first: nothing is downloaded or written for a bad command.
ORG="${KAPABLE_MW_ORG:-}"
case "$ORG" in
'' | *[!a-z0-9-]*)
	fail "The organisation name in the command is missing or not valid. Copy the command again from System Settings > MoneyWorks." \
		"KAPABLE_MW_ORG: use lowercase letters, digits and hyphens only" 2
	;;
esac
if [ "${#ORG}" -gt 63 ]; then
	fail "The organisation name in the command is not valid. Copy the command again from System Settings > MoneyWorks." \
		"KAPABLE_MW_ORG: at most 63 characters" 2
fi
CODE_REST="${KAPABLE_MW_CODE:-}"
case "$CODE_REST" in
mwe_?*) CODE_REST="${CODE_REST#mwe_}" ;;
*)
	fail "The install code in the command is missing or not valid. Copy the command again from System Settings > MoneyWorks." \
		"KAPABLE_MW_CODE: set mwe_ followed by base64url characters" 2
	;;
esac
case "$CODE_REST" in
*[!A-Za-z0-9_-]*)
	fail "The install code in the command is not valid. Copy the command again from System Settings > MoneyWorks." \
		"KAPABLE_MW_CODE: only A-Z a-z 0-9 - _ may follow mwe_" 2
	;;
esac
export KAPABLE_MW_CODE

for pin in "$AGENT_URL_DARWIN_ARM64" "$AGENT_SHA256_DARWIN_ARM64" "$AGENT_URL_DARWIN_X86_64" \
	"$AGENT_SHA256_DARWIN_X86_64" "$CONNECTOR_KEY" "$UNINSTALL_URL"; do
	case "$pin" in
	*@@*) fail "This installer is not finished and cannot be used. Download it again from the link in System Settings > MoneyWorks." \
		"a publish placeholder was not filled in (run render.sh)" 1 ;;
	esac
done

# 2. Platform.
OS="$(uname -s)"
ARCH="$(uname -m)"
if [ "$OS" != "Darwin" ]; then
	fail "This installer is for Mac computers (Apple silicon or Intel). On Windows, use the PowerShell command from System Settings > MoneyWorks." \
		"uname -s is $OS; supported: Darwin arm64, Darwin x86_64" 2
fi
case "$ARCH" in
arm64)
	AGENT_URL="$AGENT_URL_DARWIN_ARM64"
	AGENT_SHA256="$AGENT_SHA256_DARWIN_ARM64"
	;;
x86_64)
	AGENT_URL="$AGENT_URL_DARWIN_X86_64"
	AGENT_SHA256="$AGENT_SHA256_DARWIN_X86_64"
	;;
*)
	fail "This Mac's processor type is not supported. The agent runs on Apple silicon and Intel Macs." \
		"uname -m is $ARCH; supported: arm64, x86_64" 2
	;;
esac
if [ "$(id -u)" = "0" ]; then
	fail "Run this command as yourself, without sudo." \
		"the agent is a per-user LaunchAgent; running as root would install it for root" 2
fi
if [ -z "${HOME:-}" ] || [ ! -d "$HOME" ]; then
	fail "Your home folder could not be found." "HOME is not set to a folder" 1
fi

BASE="$HOME/.kapable-mw-agent"
DIR="$BASE/$ORG"
LABEL="ai.kapable.mw-agent-$ORG"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
LOG="$DIR/agent.log"
ENROL_URL="$(printf '%s' "$ENROL_URL_TEMPLATE" | sed "s/<org>/$ORG/")"
REMOVE_CMD="curl -fsSL $UNINSTALL_URL | KAPABLE_MW_ORG=$ORG sh"

for folder in "$BASE" "$DIR"; do
	if [ -L "$folder" ]; then
		fail "The agent folder is a link, so the set-up stopped to keep the keys safe. Remove $folder and run the command again." \
			"$folder is a symbolic link" 1
	fi
	if [ -e "$folder" ] && { [ ! -d "$folder" ] || [ ! -O "$folder" ]; }; then
		fail "The agent folder is not a folder you own, so the set-up stopped to keep the keys safe. Remove $folder and run the command again." \
			"$folder is not a directory owned by $(id -un)" 1
	fi
done
# Any content at all means an agent (or a half-removed one) lives here.
if [ -d "$DIR" ] && [ -n "$(ls -A "$DIR")" ]; then
	fail "An agent for $ORG is already set up on this computer. Remove it first: $REMOVE_CMD" \
		"$DIR exists and is not empty" 2
fi
if [ -e "$PLIST" ] || [ -L "$PLIST" ]; then
	fail "An agent for $ORG is already set up on this computer. Remove it first: $REMOVE_CMD" \
		"$PLIST exists" 2
fi

say() { printf '%s\n' "$1"; }

# 3. Download and check the agent.
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/kapable-mw-agent.XXXXXX")"
say "Downloading the Kapable MoneyWorks agent..."
if ! curl -fsSL --proto '=https' --tlsv1.2 --retry 2 -o "$TMP_DIR/burrow-agent" "$AGENT_URL"; then
	fail "The agent could not be downloaded. Check this computer can reach the internet, then run the command again." \
		"download of $AGENT_URL failed" 1
fi
sha256_of() {
	if command -v shasum >/dev/null 2>&1; then
		shasum -a 256 "$1" | cut -d ' ' -f 1
	else
		openssl dgst -sha256 -r "$1" | cut -d ' ' -f 1
	fi
}
GOT_SHA="$(sha256_of "$TMP_DIR/burrow-agent" | tr 'A-F' 'a-f')"
WANT_SHA="$(printf '%s' "$AGENT_SHA256" | tr 'A-F' 'a-f')"
if [ "$GOT_SHA" != "$WANT_SHA" ]; then
	rm -f "$TMP_DIR/burrow-agent"
	fail "The downloaded agent is not the published one, so it was deleted and nothing was installed. Try again later." \
		"SHA-256 of $AGENT_URL is $GOT_SHA, the installer pins $WANT_SHA" 1
fi

# 4. Private folder, then the binary, then keys (through the agent).
# The org folder is always made fresh (an empty leftover is removed first), so
# nothing in it predates this run and nothing is written through a link.
if [ ! -d "$BASE" ]; then
	mkdir -m 700 "$BASE"
fi
chmod 700 "$BASE"
if [ -d "$DIR" ]; then
	rmdir "$DIR"
fi
if ! mkdir -m 700 "$DIR"; then
	fail "The agent folder could not be made. Remove $DIR and run the command again." "mkdir $DIR failed" 1
fi
undo_folder() {
	rm -rf "$DIR"
}
AGENT="$DIR/burrow-agent"
mv -f "$TMP_DIR/burrow-agent" "$AGENT"
chmod 700 "$AGENT"
xattr -c "$AGENT" 2>/dev/null || true
if ! "$AGENT" --help >/dev/null 2>&1; then
	# An unsigned or ad-hoc signed binary can be refused after a copy; re-sign locally.
	codesign --force --sign - "$AGENT" >/dev/null 2>&1 || true
	if ! "$AGENT" --help >/dev/null 2>&1; then
		undo_folder
		fail "This Mac would not start the agent. Check the Mac is up to date, then run the command again." \
			"$AGENT --help did not run (even after an ad-hoc codesign)" 1
	fi
fi

set +e
"$AGENT" moneyworks-enrol --dir "$DIR" --org "$ORG" --enrol-url "$ENROL_URL" --connector-key "$CONNECTOR_KEY"
RC=$?
set -e
if [ "$RC" -ne 0 ]; then
	# The agent printed its two lines and removed its own files.
	undo_folder
	exit "$RC"
fi

# 5. LaunchAgent: start now and at every login, restart if it stops.
xml_escape() {
	printf '%s' "$1" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g'
}
# noclobber: creating either file fails if anything (a link included) is there.
if [ -e "$LOG" ] || [ -L "$LOG" ]; then
	fail "The agent folder changed during the set-up. Remove $DIR and run the command again." "$LOG appeared" 1
fi
set -C
: >"$LOG"
set +C
mkdir -p "$HOME/Library/LaunchAgents"
if [ -L "$PLIST" ] || [ -e "$PLIST" ]; then
	fail "An agent for $ORG is already set up on this computer. Remove it first: $REMOVE_CMD" "$PLIST exists" 2
fi
X_AGENT="$(xml_escape "$AGENT")"
X_CONFIG="$(xml_escape "$DIR/agent.toml")"
X_DIR="$(xml_escape "$DIR")"
X_LOG="$(xml_escape "$LOG")"
set -C
cat >"$PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Label</key>
	<string>$LABEL</string>
	<key>ProgramArguments</key>
	<array>
		<string>$X_AGENT</string>
		<string>--config</string>
		<string>$X_CONFIG</string>
	</array>
	<key>WorkingDirectory</key>
	<string>$X_DIR</string>
	<key>EnvironmentVariables</key>
	<dict>
		<key>NO_COLOR</key>
		<string>1</string>
	</dict>
	<key>RunAtLoad</key>
	<true/>
	<key>KeepAlive</key>
	<true/>
	<key>ThrottleInterval</key>
	<integer>10</integer>
	<key>StandardOutPath</key>
	<string>$X_LOG</string>
	<key>StandardErrorPath</key>
	<string>$X_LOG</string>
</dict>
</plist>
EOF
set +C
chmod 644 "$PLIST"
UID_NOW="$(id -u)"
if ! launchctl bootstrap "gui/$UID_NOW" "$PLIST" 2>/dev/null; then
	if ! launchctl load -w "$PLIST" 2>/dev/null; then
		fail "The agent is set up but could not be started. Sign in to this Mac's desktop and run: launchctl load -w $PLIST" \
			"launchctl bootstrap gui/$UID_NOW and launchctl load both failed" 1
	fi
fi

# 6. Wait up to 30 s for the tunnel. The agent logs "registering tunnel" once
# its connection to Kapable is open; a refused sign-in closes it again.
connected() {
	last="$(grep -n 'registering tunnel' "$LOG" 2>/dev/null | tail -n 1 | cut -d : -f 1)"
	[ -n "$last" ] || return 1
	if tail -n +"$((last + 1))" "$LOG" | grep -q -e 'disconnected' -e 'server closed connection' -e 'run_once failed' -e 'ws read error'; then
		return 1
	fi
	return 0
}
waited=0
state="no"
while [ "$waited" -lt 30 ]; do
	if connected; then
		sleep 3
		if connected; then
			state="yes"
			break
		fi
	fi
	sleep 1
	waited=$((waited + 1))
done
if [ "$state" = "yes" ]; then
	say "Connected."
	say "Finish in System Settings > MoneyWorks: check the pairing code shown above matches, then approve."
else
	say "Not connected yet: check this computer can reach the internet, then look at $LOG"
fi
