#! /usr/bin/env bash

set -eo pipefail

if [ "$EUID" -eq 0 ]; then
	echo "Do not run this as root (do not use sudo)" >&2
	exit 1
fi

# Find the site CA file, which also tells us the client package name.
SITE_CA_FILES=(/usr/local/share/ca-certificates/*-site-ca-ca.crt)

if [ "${#SITE_CA_FILES[@]}" -ne 1 ]; then
	echo "Found ${#SITE_CA_FILES[@]} legacy installations, expected 1" >&2
	exit 1
elif ! [ -f "${SITE_CA_FILES[0]}" ]; then
	echo "No legacy installation found" >&2
	exit 1
fi

LEGACY_PKG=
if [[ "${SITE_CA_FILES[0]}" =~ /usr/local/share/ca-certificates/(.*)-ca.crt ]]; then
	LEGACY_PKG="${BASH_REMATCH[1]}"
else
	echo "Can't find legacy package name in $(basename "${SITE_CA_FILES[0]}")" >&2
	exit 1
fi

# Match a regex against stdin and print just capture group 1.
get_regex_group_results() {
	local regex="$1"
	gawk '{ if(match($0, "'"$regex"'", m)) { print m[1] } }'
}

# Match a regex against stdin, print just capture group 1, and verify that it
# matches exactly once.  Returns unsuccessfully if it does not match exactly
# once.
get_single_regex_group_result() {
	local regex="$1" line

	get_regex_group_results "$regex" | (
		IFS= read -r line
		echo "$line"
		if IFS= read -r line; then
			echo "Too many matches for $regex" >&2
			exit 1
		fi
	)
}

# We have to extract the values that were used in substitutions in the legacy
# package
LEGACY_DOMAIN="$(<"/usr/bin/$LEGACY_PKG-pwas" get_single_regex_group_result \
	'Manage web apps for (.*)\\.')"
LEGACY_SSH_USER="$(<"/usr/bin/$LEGACY_PKG-client" get_single_regex_group_result \
	"'([^@]+)@.+',")"
LEGACY_SSH_HOST="$(<"/usr/bin/$LEGACY_PKG-client" get_single_regex_group_result \
	"'[^@]+@(.+)',")"
LEGACY_SSH_PORT="$(<"/usr/bin/$LEGACY_PKG-client" get_single_regex_group_result \
	"'-p', '([0-9]+)',")"
LEGACY_SCRIPTS_DIR="$(<"/usr/bin/$LEGACY_PKG-client" get_single_regex_group_result \
	"bash '(.*)/sign-return-client.sh'")"

LEGACY_CA_CONTENT="$(cat "${SITE_CA_FILES[0]}")"
LEGACY_SSH_HOSTKEY="$(cat "/usr/share/$LEGACY_PKG-client/known_hosts")"

if [ -e ~/.pqccomms-client ]; then
	echo "There is already a config at ~/.pqccomms-client, can't overwrite it" >&2
	exit 1
fi

if ! [ -d ~/".$LEGACY_PKG" ]; then
	# There doesn't seem to be any legacy client setup.  While we could
	# still create a site.json and install the CA cert, this is not likely
	# to be what you want.  If we did that by mistake, then it would not be
	# easy to recover.  Bail out.
	echo "There is no legacy client setup for this user" >&2
	exit 1
fi

# Do all of the root steps first.
sudo pqccomms-legacy-ca-import-uninstall "$LEGACY_PKG"

# Move client common name and/or certs.
mv ~/".$LEGACY_PKG" ~/.pqccomms-client

# Create the site JSON
echo '{}' | jq --arg LEGACY_DOMAIN "$LEGACY_DOMAIN" \
	--arg LEGACY_SSH_USER "$LEGACY_SSH_USER" \
	--arg LEGACY_SSH_HOST "$LEGACY_SSH_HOST" \
	--arg LEGACY_SSH_PORT "$LEGACY_SSH_PORT" \
	--arg LEGACY_SSH_HOSTKEY "$LEGACY_SSH_HOSTKEY" \
	--arg LEGACY_CA_CONTENT "$LEGACY_CA_CONTENT" \
	--arg LEGACY_SCRIPTS_DIR "$LEGACY_SCRIPTS_DIR" \
	'{ca:$LEGACY_CA_CONTENT, domain:$LEGACY_DOMAIN, ssh: {hostkey:$LEGACY_SSH_HOSTKEY, user:$LEGACY_SSH_USER, host:$LEGACY_SSH_HOST, port:$LEGACY_SSH_PORT}, scripts:$LEGACY_SCRIPTS_DIR}' \
	>~/.pqccomms-client/site.json

# Restart the Firefox ESR runtime since we changed the autoconfig files by
# uninstalling the legacy package
systemctl --user restart firefoxesr-pwa-runtime

echo "Complete.  Close all $LEGACY_DOMAIN apps and open them again." >&2
