#!/bin/sh
# Copyright (C) 2004 g10 Code GmbH
#
# This file is part of Poldi.
#
# Poldi is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Poldi is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
# License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA

RSA_KEY_ID=1
RSA_KEY_ELEMENTS_N=2

if [ $# != 2 ]; then
    echo "Usage: $0 <key-id> <key-no>" >&2
    exit 1
fi

key_id=$1
key_no=$2

gpg_output=$(gpg --with-key-data --list-key $1)
pub_key=$(echo -e "$gpg_output" | grep "^pub")
pub_key_type=$(echo -e "$pub_key" | cut -d : -f 4)

if [ "$pub_key_type" != "$RSA_KEY_ID" ]; then
    echo "Invalid key" >&2
    exit 1
fi

key_data=$(echo -e "$gpg_output" | \
  awk -F : "BEGIN         { key_idx = -1; } \
            /^(pub|sub):/ { if (key_idx < $key_no) \
                               key_idx = key_idx + 1; } \
            /^pkd:/       { if (key_idx == $key_no) \
                               { print \$4; \
                                 pkd_seen = 1; } } \
            //            { if (key_idx == $key_no && pkd_seen == 1 && \$1 != \"pkd\") \
                               exit; }")
key_data_n=$(echo "$key_data" | wc -l)			       

if [ $key_data_n != $RSA_KEY_ELEMENTS_N ]; then
    echo "Invalid key data" >&2
    exit 1
fi

cat <<EOF
(public-key
 (rsa
  (n #$(echo -e "$key_data" | head -1 | tail -1)#)
  (e #$(echo -e "$key_data" | head -2 | tail -1)#)))
EOF

exit 0
