#!/usr/bin/env bash
# asn1 -- convenience wrapper for dumpasn1
#
# The dumpasn1 tool doesn't base64-decode input on its own, and won't
# completely decode unseekable input such as stdin or pipes.

. lib.bash || exit

options=()
inputs=()
waitarg=0
optend=0

for arg; do
	if (( optend )); then
		inputs+=("$arg")
	elif (( waitarg )); then
		options+=("$arg")
		waitarg=0
	elif [[ $arg == -[cfwm] ]]; then
		options+=("$arg")
		waitarg=1
	elif [[ $arg == -- ]]; then
		options+=("$arg")
		optend=1
	elif [[ $arg == -[!-]* ]]; then
		options+=("$arg")
	elif [[ $arg == --help ]]; then
		dumpasn1 --help
		exit 0
	else
		inputs+=("$arg")
	fi
done

if (( ! ${#inputs[@]} )); then
	if [[ -t 0 ]]; then
		vdie "no input files"
	fi
	inputs+=("-")
fi

r=0
for arg in "${inputs[@]}"; do
	tmp=()
	if [[ $arg == "-" ]]; then
		buf=$(mktemp /tmp/asn1.XXXXXXXX)
		tmp+=("$buf")
		cat > "$buf"
		arg=$buf
	fi
	if grep -qs "^-----" "$arg"; then
		raw=$(mktemp /tmp/asn1.XXXXXXXX)
		tmp+=("$raw")
		sed -n '/^-----BEGIN .*-----/,/^-----END .*-----/ {
				s/\r//g; /^[A-Za-z0-9+/=]*$/p
			}' "$arg" | base64 -d > "$raw"
		arg=$raw
	fi

	dumpasn1 "${options[@]}" -- "$arg" || r=1

	if (( ${#tmp[@]} )); then
		rm -f "${tmp[@]}"
	fi
done
exit $r
