#!/bin/bash -pe
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright 2001-2024, Gerrit-John Los <los@lugons.org>

# - setup -
# make wlc overridable because of chrome cut-and-paste bug
wlc=(wl-copy --paste-once)
default_timeout=3s
tags=(user password)

# - option processing -
usage() {
	cat <<-EOT 1>&2
	usage: $prog [-h] [-C] [-t TIMEOUT] [CREDENTIALS]
	   -h: show this help
	   -t: set timeout (default: $default_timeout)
	   -C: work around chrome bug
	EOT
	exit 1
}

timeout="$default_timeout"
while getopts "ht:C" opt ;do
	case "$opt" in
		h) usage ;;
		t) timeout="$OPTARG" ;;
		C) wlc=(wl-copy) ;;
		--) break ;;
		*) usage ;;
	esac
done
shift $((OPTIND-1))
[ $# -le 1 ] || usage


# - main -
trap 'echo timed out 1>&2 ' EXIT
declare -i n=0

clip() {
	# wlc has no forground/background options.  Instead -silent goes
	# into the background and is quiet; -quiet stays in the forground
	# but isn't quiet at all.
	if [ -n "$cur_val" ] ;then
		echo -n "$cur_tag..."
		timeout "$timeout" "${wlc[@]}" 2>/dev/null <<<"$cur_val"
	else
		echo -n "${tags[$n]:-?}..."
		timeout "$timeout" "${wlc[@]}" 2>/dev/null <<<"$cur_tag"
		let ++n
	fi
	echo ''
}

cat "$@" | {
	read cur_tag cur_val
	while read next_tag next_val ;do
		clip
		cur_tag="$next_tag"
		cur_val="$next_val"
	done
	clip
}

trap 'echo .' EXIT
