#!/usr/bin/python
#coding:utf-8

import os
import sys
import hashlib

def GetFileMD5(filename):
    myhash = hashlib.md5()
    with open(filename, 'rb') as f:
        while True:
            b = f.read(8096)
            if not b: 
                break
            myhash.update(b)
    return myhash.hexdigest()

def running(path):
    rpmlist = []
    for root, dirs,files in os.walk(path):
        if root.endswith("RedHat"):
            (roll, version, arch) = root.split(os.path.sep)[-4:-1]
            rollname = "%s/%s/%s" % (roll, version, arch)
            rollvers = "%s-%s-%s" % (roll, version, arch)

            baseDirs = os.path.join(rollname, 'RedHat', 'RPMS')
            for f in os.listdir(baseDirs):
                rpmname = os.path.join(baseDirs, f)
                md5sum  = GetFileMD5(rpmname)
                result  = "%s %s %s" % (md5sum, rollvers, rpmname)
                rpmlist.append(result)

    return rpmlist

if __name__ == "__main__":
    args = sys.argv
    if len(args) < 2:
        print " - Must to be supply an path."
        sys.exit(0)

    path = args[1]
    if os.path.isdir(path) and path != '/':
        path = os.path.abspath(path)
        rpmlist = running(path)

        rfile = os.path.join(path, 'rollslist')
        with open(rfile, 'w') as f:
            f.write('\n'.join(rpmlist))
            f.write('\n')
