#!/usr/bin/python

import sys, os
from gpgwrapper import sig_checks_enabled, check_sig, SignatureError, CHECK_SIGS_FLAG

from optparse import OptionParser

USAGE_ERR = 1
NO_CHECK_ERR = 2
BADSIG_ERR = 4


parser = OptionParser(usage="%prog [-S] [-q] [-f SIG] FILE [FILE [..]] || %prog -t")
parser.add_option("-t", "--test-security", action="store_true",
                  help="say whether checking would happen or not")
parser.add_option("-S", "--strict", action="store_true",
                  help="cause an error if %s is unset" % CHECK_SIGS_FLAG)
parser.add_option("-q", "--silent", action="store_true",
                  help="no output: error codes only")
parser.add_option("-f", "--sig-file",
                  help="signature file (default: {filename}.sig)")

options, files = parser.parse_args()

def maybe_say(msg):
    if not options.silent:
        print >> sys.stdout, msg

# --test-security tells you whether the check would be made or not.
if options.test_security:
    if files:
        print parser.get_usage()
        sys.exit(USAGE_ERR)
    if sig_checks_enabled():
        maybe_say("Security checks are enabled")
        sys.exit(0)
    maybe_say("Security checks are not enabled")
    sys.exit(NO_CHECK_ERR)

if not files:
    print parser.get_usage()
    sys.exit(USAGE_ERR)

if options.sig_file and len(files) > 1:
    print "Can only check one file per named sig_file"
    sys.exit(USAGE_ERR)

sig_file = options.sig_file or None

if not sig_checks_enabled():
    #if options strict is set, this is an error
    if options.strict:
        maybe_say("ERROR: Signature checking is turned off in strict mode (no %s)" % CHECK_SIGS_FLAG)
        sys.exit(NO_CHECK_ERR)

    #otherwise, it is not an error, and there is nothing to be done.
    maybe_say("WARNING: Signature checking is turned off - nothing was checked.")
    sys.exit(0)

#so, if we got this far, sig_checks are enabled.

failures = []
for f in files:
    try:
        ok = check_sig(f, sig_file)
        if ok is None:
            maybe_say("WARNING: signature checking appears to be off, but a microsecond ago it was on")

    except SignatureError, e:
        failures.append("%-28s: %s" %(f, e))
        if options.silent:
           sys.exit(BADSIG_ERR)

if failures:
    for line in failures:
        print line
    sys.exit(BADSIG_ERR)
