#!/bin/sh -efu

. shell-error

if [ "${1-}" = '--edit' ]; then
	edit_key=1
	shift
else
	edit_key=
fi
keyfile="$1"; shift
uid_pattern='.*[[:space:]]+<[^@]+(@| at )(altlinux|etersoft)(\.| dot )(com|net|org|ru)>$'

read_keycode()
{
    gpg --list-keys --with-colons| grep '^pub:'|cut -f4 -d:
}

make_sublist()
{
    gpg --list-keys --with-colons|
	grep '^sub:'|
	grep -n '.*'|
	while IFS=':' read num _ _ _ _ _ _ _ _ _ _ _ caps _; do
	    echo "$caps"|grep -qs 's' || echo "$num"
	done
}

strip_sub()
{
	local sublist="$(make_sublist)"

	[ -n "$sublist" ] || return 0

	(for i in $sublist; do echo "key $i"; done
	 echo delkey
	 echo Y
	 echo save)|
		gpg --no-greeting --no-tty --command-fd=0 --edit-key "$1"
}

make_uidlist()
{
    gpg --list-keys --with-colons|
	egrep '^(pub|uid|uat):'|
	grep -n '.*'|
	while IFS=':' read num type _ _ _ _ _ _ _ _ comment _ _ _; do
	    case "$type" in
		pub|uid)
		    echo "$comment"|egrep -qs "$uid_pattern" || echo "$num"
		;;
		uat)
		echo "$num"
		;;
	    esac
	done
}

strip_uid()
{
	local uidlist="$(make_uidlist)"

	[ -n "$uidlist" ] || return 0

	(for i in $uidlist; do echo "uid $i"; done
	 echo deluid
	 echo Y
	 echo save)|
		gpg --no-greeting --no-tty --command-fd=0 --edit-key "$1"
}

tempdir=
cleanup_handler()
{
	trap - EXIT
	[ -z "$tempdir" ] || rm -rf "$tempdir"
	exit "$@"
}

exit_handler()
{
	cleanup_handler $?
}

signal_handler()
{
	cleanup_handler 143
}

trap exit_handler EXIT
trap signal_handler HUP PIPE INT QUIT TERM
tempdir="$(mktemp -td alt-gpgkeys.XXXXXX)"

export LANG=C
export GNUPGHOME="$tempdir"

gpg --import "$keyfile" 2>/dev/null ||
	fatal "$keyfile: Invalid gpg key file"

keycode="$(gpg --list-keys --with-colons| grep '^pub:'|cut -f5 -d:)"

[ -n "$keycode" ] ||
	fatal "$keyfile: Unable to calculate key code"
n="$(printf '%s\n' "$keycode" |wc -l)"
[ "$n" = 1 ] ||
	fatal "$keyfile: Too many ($n) keys found"

strip_sub "$keycode"
strip_uid "$keycode"
[ -z "$edit_key" ] || gpg --edit-key "$keycode"

echo "Key content:"
gpg --list-keys

tempkeyfile="$tempdir/gpgkey"
cp -p "$keyfile" "$tempkeyfile"
gpg --export --armor "$keycode" >"$tempkeyfile" ||
	fatal 'Unable to export gpg key'
mv -f "$tempkeyfile" "$keyfile"
