#!/bin/sh
set -f

[ "$1" = get ] || exit

while read -r line; do
	case $line in
		protocol=*)
			protocol=${line#*=} ;;
		host=*)
			host=${line#*=} ;;
		username=*)
			user=${line#*=} ;;
		path=*)
			path=${line#*=} ;;
	esac
done

output=
#shellcheck disable=2154
for arg in \
	"${protocol:+$protocol://}$host${path:+/$path}" \
	"$host" \
	"${host2=${host%.*}}" \
	"${host2#*.}"
do
	# exit on first good result
	[ -n "$user" ] && output=$(bwx get --full "$arg" "$user") && break
	output=$(bwx get --full "$arg") && break
done || exit

printf '%s\n' "$output" | sed -n '
	1{ s/^/password=/p }
	s/^Username: /username=/p
	s/^URI: /host=/p
	'
