#!/usr/bin/perl
#
#  Copyright 2002-2006 Ingo Kloecker <mail@ingo-kloecker.de>
#
#  This program 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.
#
#  This program 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

use strict;

my $myKeyID="0123456789ABCDEF";
my $myEmailAddress="Full Name <name\@example.com>";
my $myFirstName="Firstname";
my $occasion="something";

foreach my $keyID (@ARGV) {
    if ( $keyID !~ /[A-F0-9]{8}/i )
    {
        die "\"$keyID\" doesn't look like a valid Key-ID!\n";
    }

    printf stderr "Key ID: $keyID\n";

    my (%uids);

    open( GPG, "gpg --with-colon --list-sigs --fixed-list-mode $keyID 2>/dev/null|" )
        || die "Cannot run gpg\n";

    my $uid = "";

    while ( <GPG> ) {
        if ( /^uid/ ) {
            if ( defined( $uid ) && $uid ne "" ) {
                $uids{$uid} = $uid;
            }
            my @fields = split /:/;
            if ( ( $fields[1] ne "r" ) && ( $fields[1] ne "e" ) ) {
                # user ID wasn't revoked and hasn't expired
                $uid = $fields[9];
                # convert some UTF-8 to latin1
                $uid =~ s/Ã\\x9f/ß/g;
                $uid =~ s/Ã\\x89/É/g;
                $uid =~ s/Ã¤/ä/g;
                $uid =~ s/Ã¡/á/g;
                $uid =~ s/Ã©/é/g;
                $uid =~ s/Ã¨/è/g;
                $uid =~ s/Ã¸/ø/g;
                $uid =~ s/Ã¶/ö/g;
                $uid =~ s/Ã¼/ü/g;
                $uid =~ s/Ä\\x8c/C/g;
                $uid =~ s/Å\\x99/r/g;
                $uid =~ s/\\x3a/:/g;
                printf STDERR "Found valid user id $uid.\n"
            }
        }
        elsif ( /^sig.*:$myKeyID:.*x:$/ ) {
            $uid = "";
            printf STDERR "This user id was already signed by me.\n"
        }
    }
    close GPG;

    if ( defined( $uid ) && $uid ne "" ) {
        $uids{$uid} = $uid;
    }

    foreach $uid ( keys %uids )
    {
        # Get a random string:
        my $challenge;
        open ( RANDOM, "head -c 18 /dev/urandom | mimencode|" )
            || die "Cannot get random string\n";
        while ( <RANDOM> )
        {
            $challenge .= $_;
        }
        chomp $challenge;
        close RANDOM;

        # Create the encrypted part of the body of the message:
        my $body = << "EOF";
[Weiter unten steht dasselbe auf deutsch.]

This message is sent as part of my certification process.
It is to verify that you, the keyholder of $keyID can read email
sent to the associated address
$uid

Please, now that you have decrypted this message, simply reply to
  $myEmailAddress
quoting

> KeyID: $keyID
> UserID: $uid
> Magic: $challenge
> Upload to keyserver after signing: yes

in the body of your message.

If you asked me to certify more than one userid or email address
on your key you should receive one of these messages for each
address - in that case please send one reply per address, too.

After signing your key I will upload it to the keyserver network
unless you oppose.

-----

Diese Nachricht ist Teil meines Zertifizierungsprozesses. Damit
überprüfe ich, dass du, der Besitzer des OpenPGP-Schlüssels $keyID,
die E-Mail-Adresse
$uid
kontrollierst.

Jetzt nachdem du diese Nachricht entschlüsselt hast, sende einfach
eine Antwort an
  $myEmailAddress
wobei du Folgendes zitierst:

> KeyID: $keyID
> UserID: $uid
> Magic: $challenge
> Schlüssel nach dem Signieren hochladen: ja

Falls du mich gebeten hast, mehrere UserIDs oder E-Mail-Adressen zu
zertifizieren, dann solltest du für jede Adresse eine dieser Nachrichten
erhalten. In diesem Fall sende bitte für jede Nachricht eine separate
Antwort.

Nachdem ich deinen Schlüssel signiert habe, werde ich ihn auf einen
oder mehrere Keyserver hochladen, sofern du dem nicht widersprichst.
EOF
        # encrypt the message
        my $tempfile="$keyID.ttt";
        open( GPG, "|gpg --batch --encrypt --armor --textmode -r 0x$myKeyID \
--encrypt-to $keyID >$tempfile" )  || die "Cannot run gpg\n";
        print GPG $body;
        close GPG;
        open( FILE, $tempfile )
            || die "File '$tempfile' doesn't exist\n";
        my $encbody;
        while ( <FILE> )
        {
          $encbody .= $_;
        }
        close FILE;
        unlink $tempfile;

        $body = << "EOF";
[Weiter unten steht dasselbe auf deutsch.]

Hi!

You are being sent this message because we exchanged OpenPGP key
fingerprints at $occasion and you asked me to sign your
key(s).

Please decrypt the encrypted message for instructions on how to
complete the certification protocol.

If you don't know what I'm talking about, then please reply to me as
soon as possible, since someone other than yourself tried to make me
certify that the OpenPGP key with ID 0x$keyID does belong to you.
In other words, someone tried to STEAL YOUR IDENTITY.

Regards
$myFirstName

-----

Hallo!

Wir haben in $occasion Fingerprints unserer OpenPGP-Schlüssel
ausgetauscht, und du hast mich gebeten, deinen Schlüssel zu
signieren.

Die folgende verschlüsselte Nachricht erklärt, was du tun musst, damit
ich deinen Schlüssel zertifiziere.

Falls du nicht weißt, wovon ich rede, dann solltest du mich umgehend
darüber informieren, da in diesem Fall jemand versucht deine E-Mail-
Adresse als seine zu verkaufen.

Viele Grüße
$myFirstName

EOF
        $body .= $encbody;
        #open( MAIL, "|mail -s \"OpenPGP key exchange formalities\" \"$uid\"" )
        #    || die "Cannot run mail\n";
        #print MAIL $encbody;
        #close MAIL;

        # using DCOP interface
        # openComposer( QString to, QString cc, QString bcc,
        #               QString subject, QString body, bool hidden )
        open ( DCOP , "dcop kmail default openComposer \"$uid\" \"\" \"\" \"OpenPGP \
key certification challenge\" \"$body\" false|" ) || die "Cannot access Kmail DCOP \
interface\n";  my $dcopRef = <DCOP>;
        close DCOP;
        chomp $dcopRef;
        
        print "$challenge: $uid ($keyID)\n";
    }
}
