#!/usr/bin/python

# Copyright (C) 2011 Serafeim Zanikolas <sez@debian.org>
#
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import sys
import commands
import os

infile = sys.argv[1]

mismatches = False

diff = open('%s.diff' % infile, 'w')
for line in open(infile):
    fields = line.split()
    name = fields[0]
    keyid = ''.join(fields[-2:])
    known_fingerprint = " ".join(fields[2:])
    status, output = commands.getstatusoutput('gpg --fingerprint %s' % keyid)
    if status != 0:
        print 'no key stored for keyid %s (%s)' % (keyid, name)
        continue
    fingerprint_line = [line for line in output.split('\n')
            if 'Key fingerprint' in line]
    if not fingerprint_line:
        print 'failed to parse fingerprint for keyid %s (%s)' % (keyid, name)
        continue
    stored_fingerprint = ' '.join(fingerprint_line[0].split()[3:])

    if known_fingerprint == stored_fingerprint:
        print keyid, 'ok'
    else:
        print keyid, 'nok'
        print known_fingerprint
        print stored_fingerprint
        print
        mismatches = True
    diff.write('%s %s\n' % (name, stored_fingerprint))

diff.close()

if mismatches:
    cmd = 'wdiff %s %s.diff' % (infile, infile)
    print cmd
    os.system(cmd)
