import md5
import sha
import sys
import os
import subprocess
import getpass

def signFile(force, pwd, fileName):

  ascFileName = fileName + '.asc'

  exists = os.path.exists(ascFileName)

  if exists:
    if not force:
      result = os.system('gpg --verify %s %s' % (ascFileName, fileName))
      if result:
        raise RuntimeError('signature check of %s failed' % ascFileName)
      return pwd
    else:
      os.remove(ascFileName)

  if pwd is None:
    pwd = getpass.unix_getpass(prompt='\nPlease enter your GPG private key passphrase:')
      
  print '\nSIGN %s' % fileName

  command = 'gpg --passphrase-fd 0 --batch --armor --default-key "CODE SIGNING KEY" --detach-sig %s' % fileName
  print '  command %s' % command

  p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE)
  p.stdin.write(pwd)
  p.stdin.close()
  result = p.wait()
  if result != 0:
    raise RuntimeError('command failed: exit code %s' % result)

  return pwd

def checkMD5(fileName):
  digest = open(fileName, 'rb').read().split()[0]
  m = md5.md5()
  m.update(open(fileName[:-4], 'rb').read())
  if m.hexdigest() != digest:
    print
    print 'MD5 check failed on %s' % fileName
    print '  MD5 file says %s' % digest
    print '  but actual is %s' % m.hexdigest()
    raise RuntimeError('MD5 check failed')
  else:
    print 'MD5 OK: %s' % fileName
  
def checkSHA(fileName):
  digest = open(fileName, 'rb').read().split()[0]
  m = sha.sha()
  m.update(open(fileName[:-5], 'rb').read())
  if m.hexdigest() != digest:
    print
    print 'SHA check failed on %s' % fileName
    print '  SHA file says %s' % digest
    print '  but actual is %s' % m.hexdigest()
    raise RuntimeError('SHA check failed')
  else:
    print 'SHA OK: %s' % fileName
  
def isArtifact(fileName):
  for suffix in ('.tar.gz', '.jar', '.zip', '.pom'):
    if fileName.endswith(suffix):
      return True
  else:
    if os.path.exists(fileName + '.md5') or os.path.exists(fileName + '.sha1'):
      print 'WARNING: not signing %s yet it has a digest' % fileName
    return False

def main(argv):

  if '-force' in argv:
    argv.remove('-force')
    force = True
  else:
    force = False

  if len(argv) != 2:
    print '\nUsage: python %s distRootDirName [-force]\n' % argv[0]
    return

  pwd = None
  
  for dirPath, dirNames, fileNames in os.walk(argv[1]):
    for fileName in fileNames:
      fullPath = os.path.join(dirPath, fileName)
      if isArtifact(fileName):
        pwd = signFile(force, pwd, fullPath)
      if fileName.endswith('.md5'):
        checkMD5(fullPath)
      if fileName.endswith('.sha1'):
        checkSHA(fullPath)

if __name__ == '__main__':
  main(sys.argv)
