#!/usr/bin/env python2
"""
Read a list of filenames on stdin and copy all these files into a directory.
The file paths will be removed while copying.
"""
import sys, os, md5

if __name__ == "__main__":
    try:
        destdir = sys.argv[1]
    except IndexError:
        print "Usage:", os.path.basename(sys.argv[0]), "<destination_directory>"
        print __doc__
        sys.exit(2)

    if not os.path.isdir(destdir):
        try:
            os.mkdir(destdir)
        except OSError, e:
            print "failed to create target directory:", e
            sys.exit(1)

    try:
        idxfile = open(os.path.join(destdir, ".index"), "w")
    except IOError, e:
            print "failed to create index file:", e
            sys.exit(1)

    filemap = {}
    for line in sys.stdin:
        line = line.split('#', 1)[0].strip()
        if not line: continue
        while os.path.islink(line):
            line = os.path.normpath(os.path.join(os.path.dirname(line), os.readlink(line)))
        filemap[line.lower()] = line
    filelist = filemap.keys()
    filelist.sort()

    sums = {}
    for key in filelist:
        fullpath = filemap[key]
        filename = os.path.basename(fullpath)

        try:
            f = open(fullpath, "rb")
            data = f.read()
            f.close()
        except IOError, e:
            print >>sys.stderr, "Error reading '%s':" % fullpath, e
            continue

        s = md5.md5(data).hexdigest()
        skey = filename.lower()
        if not(skey in sums):
            sums[skey] = [s]
            index = 0
            new = True
        else:
            try:
                index = sums[skey].index(s)
                new = False
            except ValueError:
                index = len(sums[skey])
                sums[skey].append(s)
                new = True
        if index:
            f, e = os.path.splitext(filename)
            filename = "%s-%d%s" % (f, index, e)

        print "%s: %s" % (filename, fullpath)
        idxfile.write("%s\t%s\n"% (filename, fullpath))

        if new:
            outfile = os.path.join(destdir, filename)
            try:
                f = open(outfile, "wb")
                f.write(data)
                f.close()
            except IOError, e:
                print >>sys.stderr, "Error writing '%s':" % outfile, e
                continue

    idxfile.close()
