+cleanup() {
+ echo -n "removing temp gpg home... " 1>&2
+ rm -rf "$TMPPRIVATE"
+ echo "done." 1>&2
+}
+
+export_sec_key() {
+ gpg --export-secret-key "$GPGID" | GNUPGHOME="$TMPPRIVATE" gpg --import
+
+ GNUPGHOME="$TMPPRIVATE" gpg --edit-key "$GPGID"
+
+ # idea to script the password stuff. not working.
+ # read -s -p "enter gpg password: " PASSWD; echo
+ # cmd=$(cat <<EOF
+ # passwd
+ # $PASSWD
+ # \n
+ # \n
+ # \n
+ # yes
+ # save
+ # EOF
+ # )
+ # echo -e "$cmd" | GNUPGHOME="$TMPPRIVATE" gpg --command-fd 0 --edit-key $GPGID
+
+ # export secret key to file
+ GNUPGHOME="$TMPPRIVATE" gpg --export-secret-keys "$GPGID" | \
+ openpgp2ssh "$GPGID"
+}
+
+# if no hex string is supplied, just print an explanation.
+# this covers seckey2sshagent --help, --usage, -h, etc...
+if [ "$(echo "$1" | tr -d '0-9a-fA-F')" ]; then
+ explanation
+ exit
+fi
+
+# set the file creation umask
+umask 077
+
+GPGIDS="$1"
+if [ "$2" -a ! -e "$2" ] ; then
+ FILE="$2"
+fi
+
+if [ -z "$GPGIDS" ]; then
+ # hack: we need to get the list of secret keys, because if you
+ # --list-secret-keys with no arguments, GPG fails to print the
+ # capability flags (i've just filed this as
+ # https://bugs.g10code.com/gnupg/issue945)
+ KEYIDS=$(gpg --with-colons --list-secret-keys | grep ^sec | cut -f5 -d:)
+ # default to using all fingerprints of authentication-enabled keys
+ GPGIDS=$(gpg --with-colons --fingerprint --fingerprint --list-secret-keys $KEYIDS | egrep -A1 '^(ssb|sec):.*:[^:]*a[^:]*:$' | grep ^fpr: | cut -d: -f10)
+fi
+
+trap cleanup EXIT