#!/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>.
# KAPABLE_MW_INSTANCE=2..5 adds -<n> to the folder and job names.
# KAPABLE_MW_ALLOW_DOCUMENT=<name> (without KAPABLE_MW_CODE) updates an
# existing agent locally, adds the document, and restarts only its job. A failed
# restart restores the previous binary and config; keys and token are untouched.
# 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/066ecbc12a46b651a78d4a55ea73ad248a810019568dfd0ef9ca53b692ba8074'
AGENT_SHA256_DARWIN_ARM64='066ecbc12a46b651a78d4a55ea73ad248a810019568dfd0ef9ca53b692ba8074'
AGENT_URL_DARWIN_X86_64='https://releases.kapable.ai/v1/artifacts/63d80a01a9fbc6be839d655d0648d0e16ba5fb15d655479a54f6bb2e68ece2bb'
AGENT_SHA256_DARWIN_X86_64='63d80a01a9fbc6be839d655d0648d0e16ba5fb15d655479a54f6bb2e68ece2bb'
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/25bfa988c68860e1cb4ec100c0fd1da88761462afeacf0a0454dd00fe840b4e2'

TMP_DIR=''
STAGED=''
BACKUP=''
CONFIG_BACKUP=''
RESTORE=''
cleanup() {
	for temporary in "$STAGED" "$BACKUP" "$CONFIG_BACKUP" "$RESTORE"; do
		if [ -n "$temporary" ]; then rm -f "$temporary"; fi
	done
	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
SUFFIX=''
if [ "${KAPABLE_MW_INSTANCE+x}" = x ]; then
	case "$KAPABLE_MW_INSTANCE" in
	[2-5]) SUFFIX="-$KAPABLE_MW_INSTANCE" ;;
	*) fail "The agent number is not valid. Copy the command again from System Settings > MoneyWorks." \
		"KAPABLE_MW_INSTANCE: use one digit from 2 to 5" 2 ;;
	esac
fi
ALLOW_MODE=no
ALLOW="${KAPABLE_MW_ALLOW_DOCUMENT:-}"
if [ "${KAPABLE_MW_ALLOW_DOCUMENT+x}" = x ]; then
	ALLOW_MODE=yes
	if [ "${KAPABLE_MW_CODE+x}" = x ]; then
		fail "Use the add-document command without an install code." "KAPABLE_MW_ALLOW_DOCUMENT and KAPABLE_MW_CODE cannot both be set" 2
	fi
	case "$ALLOW" in
	'' | *"'"* | *'"'* | *'`'* | *'$'* | *'/'* | *'\'* | *'%'* | *'..'* | *'
'*) fail "That document name is not valid. Check the name and try again." "MW_DOCUMENT_NAME_INVALID: use a non-blank name without control characters, quotes, backticks, $, slashes, %, or .." 2 ;;
	esac
	if printf '%s' "$ALLOW" | LC_ALL=C grep -q '[[:cntrl:]]' || ! printf '%s' "$ALLOW" | LC_ALL=C grep -q '[^[:space:]]'; then
		fail "That document name is not valid. Check the name and try again." "MW_DOCUMENT_NAME_INVALID: remove blank names and control characters" 2
	fi
else
	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
fi

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$SUFFIX"
LABEL="ai.kapable.mw-agent-$ORG$SUFFIX"
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 ${KAPABLE_MW_INSTANCE:+KAPABLE_MW_INSTANCE=$KAPABLE_MW_INSTANCE }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
if [ "$ALLOW_MODE" = yes ]; then
	if [ ! -d "$DIR" ]; then
		fail "Nothing is installed for that org here. Run the install command from System Settings > MoneyWorks first." "MW_ALLOW_NOT_INSTALLED: $DIR is missing" 2
	fi
	for file in "$DIR/burrow-agent" "$DIR/agent.toml" "$LOG" "$PLIST"; do
		if [ -L "$file" ] || [ ! -f "$file" ] || [ ! -O "$file" ]; then
			fail "The installed agent's files could not be checked. Check the agent folder, then try again." "MW_ALLOW_FILES: $file must be a regular file you own" 1
		fi
	done
	UID_NOW="$(id -u)"
	if ! launchctl print "gui/$UID_NOW/$LABEL" >/dev/null 2>&1; then
		fail "The installed agent's job could not be found. Sign in to this Mac's desktop and try again." "MW_ALLOW_JOB: load $PLIST first" 1
	fi
else
	# 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
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

# Only log lines written after this run's restart may prove a connection.
LOG_START=1
connected() {
	last="$(tail -n +"$LOG_START" "$LOG" 2>/dev/null | grep -n 'registering tunnel' | tail -n 1 | cut -d : -f 1)"
	[ -n "$last" ] || return 1
	if tail -n +"$((LOG_START + last))" "$LOG" | grep -q -e 'disconnected' -e 'server closed connection' -e 'run_once failed' -e 'ws read error'; then
		return 1
	fi
	return 0
}
wait_connected() {
	waited=0
	stable=0
	while [ "$waited" -lt 30 ]; do
		sleep 1
		waited=$((waited + 1))
		if connected; then stable=$((stable + 1)); else stable=0; fi
		if [ "$stable" -ge 3 ]; then return 0; fi
	done
	return 1
}

if [ "$ALLOW_MODE" = yes ]; then
	AGENT="$DIR/burrow-agent"
	PREVIOUS="$AGENT.previous"
	CONFIG_PREVIOUS="$DIR/agent.toml.previous"
	for previous in "$PREVIOUS" "$CONFIG_PREVIOUS"; do
		if [ -L "$previous" ] || { [ -e "$previous" ] && { [ ! -f "$previous" ] || [ ! -O "$previous" ]; }; }; then
			fail "The agent backup could not be checked. Remove the backup file and try again." "MW_ALLOW_BACKUP: $previous must be a regular file you own" 1
		fi
	done
	STAGED="$(mktemp "$DIR/.burrow-agent.XXXXXX")" || fail "The downloaded agent could not be saved. Check the agent folder permissions, then try again." "MW_ALLOW_STAGE: mktemp failed" 1
	if ! cp "$TMP_DIR/burrow-agent" "$STAGED" || ! chmod 700 "$STAGED"; then
		rm -f "$STAGED"
		fail "The downloaded agent could not be saved. Check the agent folder permissions, then try again." "MW_ALLOW_COPY: staging the binary failed" 1
	fi
	xattr -c "$STAGED" 2>/dev/null || true
	if ! "$STAGED" --help >/dev/null 2>&1; then
		codesign --force --sign - "$STAGED" >/dev/null 2>&1 || true
		if ! "$STAGED" --help >/dev/null 2>&1; then
			rm -f "$STAGED"
			fail "This Mac would not start the new agent. Check the Mac is up to date, then try again." "MW_ALLOW_RUN: staged agent --help failed" 1
		fi
	fi
	BACKUP="$(mktemp "$DIR/.burrow-previous.XXXXXX")" || fail "The agent backup could not be made. Check the agent folder permissions, then try again." "MW_ALLOW_BACKUP: mktemp failed" 1
	CONFIG_BACKUP="$(mktemp "$DIR/.config-previous.XXXXXX")" || fail "The settings backup could not be made. Check the agent folder permissions, then try again." "MW_ALLOW_BACKUP: mktemp failed" 1
	if ! cp -p "$DIR/agent.toml" "$CONFIG_BACKUP" || ! mv -f "$CONFIG_BACKUP" "$CONFIG_PREVIOUS" || ! cp -p "$AGENT" "$BACKUP" || ! mv -f "$BACKUP" "$PREVIOUS" || ! mv -f "$STAGED" "$AGENT"; then
		rm -f "$STAGED" "$BACKUP"
		fail "The agent update could not be saved. Check the agent folder permissions, then try again." "MW_ALLOW_SWAP: backup or atomic rename failed; the installed binary was not changed" 1
	fi
	restore_previous() {
		RESTORE="$(mktemp "$DIR/.burrow-restore.XXXXXX")" || return 1
		cp -p "$PREVIOUS" "$RESTORE" && mv -f "$RESTORE" "$AGENT" || return 1
		RESTORE="$(mktemp "$DIR/.config-restore.XXXXXX")" || return 1
		cp -p "$CONFIG_PREVIOUS" "$RESTORE" && mv -f "$RESTORE" "$DIR/agent.toml"
	}
	if ! "$AGENT" moneyworks-allow --config "$DIR/agent.toml" --document "$ALLOW"; then
		if restore_previous; then
			fail "The document could not be added. The previous agent and settings were put back." "MW_ALLOW_FAILED: correct the refusal above, then try again" 1
		fi
		fail "The document could not be added, and the previous agent could not be put back. Contact Kapable support." "MW_ALLOW_RESTORE: restore $PREVIOUS and $CONFIG_PREVIOUS" 1
	fi
	LOG_START=$(( $(wc -l <"$LOG") + 1 ))
	if ! launchctl kickstart -k "gui/$UID_NOW/$LABEL" 2>/dev/null || ! wait_connected; then
		if restore_previous; then
			launchctl kickstart -k "gui/$UID_NOW/$LABEL" 2>/dev/null || true
			fail "The agent did not reconnect. The previous agent and settings were put back. Check the internet connection, then try again." "MW_ALLOW_RESTART: restored $PREVIOUS after restart or connection failure" 1
		fi
		fail "The agent did not reconnect, and the previous agent could not be put back. Contact Kapable support." "MW_ALLOW_RESTORE: restore $PREVIOUS and $CONFIG_PREVIOUS" 1
	fi
	say "Done: this office agent can now read $ALLOW."
	exit 0
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.
state=no
if wait_connected; then state=yes; fi
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
