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

# decrypt a file, result on stdout, 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" }
    }
    puts stderr "$argv0: $str"
    exit $s
}

if {$argc != 2} {
    puts stderr "Usage: $argv0 pubring pgpfile"
    exit 255
}

gets stdin kf
set timeout 10
log_user 0
log_file -a decryption.log
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 '$kf'; cat [lindex $argv 1]) | PGPPASSFD=0 pgpv +BATCHMODE=on >/tmp/xxx$$"]

expect {
    "Enter pass phrase:"	{ system kill $pgp; die 3 }
    -re "Error:|Cannot open"	{ die 6 }
    "BAD signature"		{ die 4 }
    "Signature by unknown key"	{ set exit_status 1 }
    timeout			{ die 2 }
}

# copy the output file to stdout
if [catch {set outfile [open /tmp/xxx$pgp r]}] { die 5 }
set contents [read $outfile]
puts -nonewline $contents

# clean up
system rm -f /tmp/xxx$pgp
exit $exit_status
