#!/usr/bin/env python
# -*- mode: python -*-

import re, time, ldap, getopt, sys, pwd, os;
from userdir_gpg import *;
Output = "extrakeys.gpg";

# Process options
AdminUser = pwd.getpwuid(os.getuid())[0];
(options, arguments) = getopt.getopt(sys.argv[1:], "o:")
for (switch, val) in options:
   if (switch == '-o'):
      Output = val

if len(arguments) == 0:
   print "Give some keyrings to probe";
   os.exit(0);

# Popen GPG with the correct magic special options
Args = [GPGPath] + GPGBasicOptions;
for x in arguments:
   Args.append("--keyring");
   if x.find("/") == -1:
      Args.append("./"+x);
   else:
      Args.append(x);
Args.append("--fast-list-mode");
Args.append("--list-sigs");
Args = Args + GPGSearchOptions + [" 2> /dev/null"]
Keys = os.popen(" ".join(Args),"r");

# Loop over the GPG key file
HaveKeys = {};
NeedKeys = {};
print "Reading keys+sigs from keyring";
while(1):
   Line = Keys.readline();
   if Line == "":
      break;
   
   Split = Line.split(":");
   if len(Split) >= 8 and Split[0] == "pub":
      HaveKeys[Split[4]] = "";
      continue;

   if len(Split) >= 5 and Split[0] == "sig":
      NeedKeys[Split[4]] = "";
      continue;
Keys.close();

# Popen GPG with the correct magic special options
Args = [GPGPath] + GPGBasicOptions;
for x in [Output]:
   Args.append("--keyring");
   if x.find("/") == -1:
      Args.append("./"+x);
   else:
      Args.append(x);
OldArgs = Args;      
Args = Args + GPGSearchOptions + [" 2> /dev/null"]
Keys = os.popen(" ".join(Args),"r");

print "Reading keys from output ring";
while(1):
   Line = Keys.readline();
   if Line == "":
      break;
   
   Split = Line.split(":");
   if len(Split) >= 8 and Split[0] == "pub":
      HaveKeys[Split[4]] = "";
      continue;
Keys.close();

KeysToFetch = [];
for x in NeedKeys.keys():
   if not HaveKeys.has_key(x):
      KeysToFetch.append("0x"+x);

print "Have %u keys and %u sigs, need %u keys"%(len(HaveKeys),len(NeedKeys),len(KeysToFetch));

Args = OldArgs;
Args.append("--keyserver 18.43.0.48");
Args.append("--recv-keys");
I = len(KeysToFetch);
while (I > 0):
   OldI = I;
   I = I - 20;
   if I < 0: I = 0;
   print " ".join(Args+KeysToFetch[I:OldI])
   Fetcher = os.popen(" ".join(Args+KeysToFetch[I:OldI]),"r");
   while(1):
      Line = Fetcher.readline();
      if Line == "":
         break;
      print Line;
   Fetcher.close();
