#!/bin/sh -efu

. shell-error

keyfile="$1"; shift
uid_pattern='.*[[:space:]]+<[^@]+(@| at )(altlinux|etersoft)(\.| dot )(com|net|org|ru)>$'

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

exit_handler()
{
	cleanup_handler $?
}

signal_handler()
{
	cleanup_handler 143
}

print_uidlist()
{
    gpg --list-keys --with-colons| egrep '^(pub|uid):'|cut -f10 -d:
}

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"

n="$(gpg --list-keys --with-colons 2>/dev/null |grep -c '^pub:')" ||
	fatal "$keyfile: No public keys found"
[ "$n" = 1 ] ||
	fatal "$keyfile: Too many ($n) keys found"

echo "Available UID:"
print_uidlist

print_uidlist|egrep -qs "$uid_pattern" ||
	fatal "$keyfile: No valid altlinux uid was found"

print_uidlist|egrep -vqs "$uid_pattern" &&
	fatal "$keyfile: Non altlinux uid detected"

gpg --list-keys --with-colons|grep '^sub:'|cut -f12 -d:|grep -vqs 's' &&
	fatal "$keyfile: Subkey detected"

exit 0
