#!/bin/sh
# Remove the Kapable MoneyWorks office agent for one organisation from this Mac
# (PLAT-2180): stops and removes the LaunchAgent ai.kapable.mw-agent-<org> and
# deletes ~/.kapable-mw-agent/<org>, keys included.
#
#   curl -fsSL https://releases.kapable.ai/<uninstaller path> | KAPABLE_MW_ORG=<org> sh
set -eu

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

ORG="${KAPABLE_MW_ORG:-}"
case "$ORG" in
'' | *[!a-z0-9-]*)
	fail "The organisation name in the command is missing or not valid." \
		"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." "KAPABLE_MW_ORG: at most 63 characters" 2
fi
if [ "$(uname -s)" != "Darwin" ]; then
	fail "This remover is for Mac computers. On Windows, use the PowerShell remover." \
		"uname -s is $(uname -s); supported: Darwin" 2
fi
if [ "$(id -u)" = "0" ]; then
	fail "Run this command as yourself, without sudo." "the agent is a per-user LaunchAgent" 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

LABEL="ai.kapable.mw-agent-$ORG"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
DIR="$HOME/.kapable-mw-agent/$ORG"

BASE="$HOME/.kapable-mw-agent"
# Refuse before removing anything if any folder from the base down is a link:
# rm -rf through a planted link could delete something else.
for folder in "$BASE" "$DIR"; do
	if [ -L "$folder" ]; then
		fail "The agent folder is a link, so nothing was removed. Remove the link $folder yourself, then run this again." \
			"$folder is a symbolic link" 1
	fi
	if [ -e "$folder" ] && [ ! -d "$folder" ]; then
		fail "The agent folder is not a folder, so nothing was removed. Remove $folder yourself, then run this again." \
			"$folder is not a directory" 1
	fi
done

found=0
UID_NOW="$(id -u)"
if launchctl print "gui/$UID_NOW/$LABEL" >/dev/null 2>&1; then
	found=1
	launchctl bootout "gui/$UID_NOW/$LABEL" 2>/dev/null || launchctl unload -w "$PLIST" 2>/dev/null || true
fi
if [ -e "$PLIST" ]; then
	found=1
	launchctl unload -w "$PLIST" 2>/dev/null || true
	rm -f "$PLIST"
fi
if [ -d "$DIR" ]; then
	found=1
	rm -rf "$DIR"
fi
rmdir "$BASE" 2>/dev/null || true

if [ "$found" = "1" ]; then
	printf '%s\n' "The MoneyWorks agent for $ORG was removed from this computer."
	printf '%s\n' "If you have not already, remove it in System Settings > MoneyWorks too."
else
	printf '%s\n' "No MoneyWorks agent for $ORG was set up on this computer, so nothing was removed."
fi
