#!/bin/sh
set -eu

readonly PROGNAME=${0##*/}
readonly VERSION=0.2.0

readonly PROXY_BIN='/usr/libexec/keepassxc-proxy.static'

readonly NAME='org.keepassxc.keepassxc_browser'
readonly DESTDIR_FIREFOX='.var/app/org.mozilla.firefox/.mozilla/native-messaging-hosts'
readonly DESTDIR_CHROMIUM='.var/app/org.chromium.Chromium/.config/chromium/NativeMessagingHosts'


help() {
	cat <<-EOF
	Usage:
	  $PROGNAME [options] <browser>

	Install proxy between Native Messaging browser extension and KeePassXC
	to your browser.

	The default <destdir> locations correspond to Flatpak applications:

	  firefox: ~/$DESTDIR_FIREFOX
	  chromium: ~/$DESTDIR_CHROMIUM

	TIP: You will also need to expose KeePassXC's BrowserServer socket to
	the Flatpak application:

	  flatpak override --filesystem=xdg-run/org.keepassxc.KeePassXC.BrowserServer:ro <app-id>

	Arguments:
	  <browser>     One of "firefox" (default), or "chromium".

	Options:
	  -d <destdir>  Override location of the native-messaging-hosts directory
	                (defaults are listed above).
	  -q            Be quiet.
	  -V            Print keepassxc-proxy version and exit.
	  -h            Show this message and exit.
	EOF
}

die() {
	printf "$PROGNAME: %s\n" "$1"
	exit 1
}

gen_manifest() {
	cat <<-EOF
	{
	  "name": "$NAME",
	  "description": "KeePassXC integration with native messaging support, workaround for flatpaked Firefox, see https://is.gd/flatpakFirefoxKPXC",
	  "path": "$DESTDIR/keepassxc-proxy",
	  "type": "stdio",
	EOF
	case "$BROWSER" in
		firefox) cat <<-EOF
		  "allowed_extensions": [
		    "keepassxc-browser@keepassxc.org"
		  ]
		EOF
		;;
		*) cat <<-EOF
		  "allowed_origins": [
		    "chrome-extension://oboonakemofpalcgghocfoadofidjkkk/"
		  ]
		EOF
		;;
	esac
	echo '}'
}

BROWSER=firefox
DESTDIR=
QUIET=false
while getopts ':d:qVh' OPT; do
	case "$OPT" in
		d) DESTDIR=$OPTARG;;
		q) QUIET=true;;
		V) echo "keepassxc-proxy-rust $VERSION"; exit 0;;
		h) help; exit 0;;
		\?) die "unknown option: -$OPTARG";;
	esac
done
shift $((OPTIND - 1))

[ $# -eq 1 ] || die "invalid number of arguments, see '$PROGNAME -h'"
BROWSER=$1

[ "$DESTDIR" ] || case "$BROWSER" in
	firefox) DESTDIR="$HOME/$DESTDIR_FIREFOX";;
	chromium) DESTDIR="$HOME/$DESTDIR_CHROMIUM";;
	*) die "unsupported browser: $BROWSER";;
esac

$QUIET || echo "Installing keepassxc-proxy for $BROWSER to $DESTDIR" >&2

install -D -m755 "$PROXY_BIN" "$DESTDIR"/keepassxc-proxy
gen_manifest > "$DESTDIR/$NAME.json"
