#!/pkg/expect/bin/expect -f

# Sign a key, exit status correct.

# generic subroutine for the suspect error cases.
proc die {s} {
    global pgp argv0

    set str "Unknown exit status"
    switch $s {
    1	{ set str "Can't check signature" }
    2	{ set str "Timeout from PGP" }
    3	{ set str "Password incorrect" }
    4	{ set str "Bad signature" }
    5	{ set str "No output file" }
    6	{ set str "Unknown error" }
    7	{ set str "More than one key matches" }
    }
    puts stderr "$argv0: $str"
    exit $s
}

if {$argc != 3} {
    puts stderr "Usage: $argv0 pubring signing_key user_key"
    exit 255
}

gets stdin kf
set timeout 10
log_user 0
set exit_status 0

# Stupid PGP has trouble switching keyrings, so I have to do it instead.
exec sh -c "rm -f pubring.pkr; cp [lindex $argv 0] pubring.pkr"

set pgp [spawn -noecho sh -c "(echo 'y'; echo '$kf') | PGPPASSFD=0 pgpk +BATCHMODE=on -s '[lindex $argv 2]' -u '[lindex $argv 1]'"]

expect {
    "Bad passphrase"		{ catch {system kill $pgp}; die 3 }
    -re "Error:|Cannot open"	{ die 6 }
    "BAD signature"		{ die 4 }
    timeout			{ die 2 }
    "Choose one of the above"	{ catch {system kill $pgp}; die 7 }
    "Duplicate certification"	{ puts stderr "Already signed" }
}

# Stupid PGP has trouble switching keyrings, so I have to do it instead.
exec cp pubring.pkr [lindex $argv 0]

# clean up
exit 0
