#! /bin/sh

if test "x$1" = "x-p"; then
	PAPERCONF=$2
	export PAPERCONF
	shift 2
fi

if [ -z "$*" ]; then
	echo "Usage: $0 keyid-or-name"
	exit 1
fi

TMPFILE=`mktemp /tmp/gpg-key2ps.XXXXXX`

if ! gpg --fingerprint --with-colons $* 2>/dev/null >$TMPFILE; then
	echo "Key not found. Try \'gpg --list-keys\'"
	rm $TMPFILE
	exit 1
fi

NUMLINES=$((`wc -l <$TMPFILE` + `grep '^pub:' $TMPFILE | wc -l` - 1))

if test -x /usr/bin/paperconf; then
	w=`paperconf -w`
	h=`paperconf -h`
else
	# Default to A4.
	w=596
	h=842
fi

cat <<EOF
%!PS-Adobe-3.0
%%BoundingBox: 0 0 $w $h
%%Title: 
%%Creator: gpg-key2ps 0.1
EOF
echo "%%CreationDate: `date`"
cat <<EOF
%%Pages: 1
%%EndComments

%%Page: 1 1

/w $w def
/h $h def

/Times-Roman findfont 9 scalefont setfont 

/newline {
	/y y 10 sub def
} def

/hline {
	30 y 3 add moveto
	w 2 div 30 sub y 3 add lineto stroke
	newline
} def

/needhline {
	/condhline { hline } def
} def

/noneedhline {
	/condhline { } def
} def

/pub {
	condhline
	50 y moveto (pub) show
	70 y moveto show show (/) show show
	150 y moveto show
	200 y moveto show
	newline
	needhline
} def

/fpr {
	70 y moveto (Key fingerprint = ) show show
	newline
} def

/uid {
	50 y moveto (uid) show
	200 y moveto show
	newline
} def

/sbk {
	50 y moveto (sub) show
	70 y moveto show show (/) show show
	150 y moveto show
	newline
} def

/key {
	noneedhline
EOF
sed -e 's/^pub:[^:]*:\([^:]*\):1:.\{8,8\}\(.\{8,8\}\):\([^:]*\):[^:]*:[^:]*:[^:]*:\([^:]*\):[^:]*:[^:]*:.*/	(\4) (\3) (\2) (R) (\1) pub/' \
    -e 's/^pub:[^:]*:\([^:]*\):17:.\{8,8\}\(.\{8,8\}\):\([^:]*\):[^:]*:[^:]*:[^:]*:\([^:]*\):[^:]*:[^:]*:.*/	(\4) (\3) (\2) (D) (\1) pub/' \
    -e 's/^fpr:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:\([^:]*\):.*/	(\1) fpr/' \
    -e 's/(\(.\{16,16\}\)\(.\{16,16\}\)) fpr/(@split@\1@  @split@\2@) fpr/' \
    -e 's/@split@\(.\{2,2\}\)\(.\{2,2\}\)\(.\{2,2\}\)\(.\{2,2\}\)\(.\{2,2\}\)\(.\{2,2\}\)\(.\{2,2\}\)\(.\{2,2\}\)@/\1 \2 \3 \4 \5 \6 \7 \8/g' \
    -e 's/(\(.\{20,20\}\)\(.\{20,20\}\)) fpr/(@split@\1@  @split@\2@) fpr/' \
    -e 's/@split@\(.\{4,4\}\)\(.\{4,4\}\)\(.\{4,4\}\)\(.\{4,4\}\)\(.\{4,4\}\)@/\1 \2 \3 \4 \5/g' \
    -e 's/^uid:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:\([^:]*\):.*/	(\1) uid/' \
    -e 's/^sub:[^:]*:\([^:]*\):16:.\{8,8\}\(.\{8,8\}\):\([^:]*\):[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:.*/	(\3) (\2) (g) (\1) sbk/' \
    <$TMPFILE
cat <<EOF
} def

EOF
echo "/numlines $(($NUMLINES + 1)) def"
cat <<EOF
/num w 16 sub 10 div numlines div def

/column {
	/y w 20 sub def
	1 1 num {
		/upper y 11 add def
		key
		newline
		/lower y 11 add def
		0 upper h 2 div upper h 2 div lower 0 lower 0 upper moveto lineto lineto lineto lineto stroke
	} for
} def

w 0 translate
90 rotate
column
h 2 div 0 translate
column

showpage

%%Trailer
%%EOF
EOF

rm $TMPFILE
