#!/usr/bin/env python2

# This is called by findup automatically don't call explicitly
# unless you really know what you're doing.
#
# It expects lines in the format:
# filename1
# filename2
#
# filename3
# filename4
# ...

import sys, string, os, tempfile, errno

symlink=0
link=1
dryRun=0
if len(sys.argv) == 2:
    if sys.argv[1] == "del":
        link=0
    elif sys.argv[1] == "tdel":
        link=0
        dryRun=1
    elif sys.argv[1] == "tmerge":
        dryRun=1
    elif sys.argv[1] == "symlink":
        symlink=1
    elif sys.argv[1] == "tsymlink":
        symlink=1
        dryRun=1

ingroup = 0
for line in sys.stdin:
    line = line[:-1]
    if line == '':
        ingroup = 0
    else:
        if not ingroup:
            keepfile = line
            ingroup = 1
            if dryRun:
                sys.stdout.write("\n\nkeeping:     " + keepfile + "\n")
                if symlink:
                    sys.stdout.write("symlinking: ")
                elif link:
                    sys.stdout.write("hardlinking: ")
                else:
                    sys.stdout.write("deleting: ")
        else:
            if dryRun:
                sys.stdout.write(line+' ')
            else:
                dupfile = line
                dupdir = os.path.dirname(dupfile)
                tmpfile = tempfile.mktemp(dir=dupdir)
                try:
                    if link:
                        try:
                            if symlink:
                                os.symlink(os.path.realpath(keepfile),tmpfile)
                            else:
                                os.link(keepfile,tmpfile)
                        except OSError, value:
                            if value.errno == errno.EXDEV and not symlink:
                                os.symlink(os.path.realpath(keepfile),tmpfile)
                            else:
                                raise
                        os.rename(tmpfile, dupfile)
                    else:
                        os.unlink(dupfile)
                except OSError:
                    sys.stderr.write(str(sys.exc_info()[1])+'\n')
                try:
                    #always try this as POSIX has bad requirement that
                    #rename(file1,file2) where both are links to the same
                    #file, does nothing, and returns success. So if user
                    #merges files multiple times, tmp files will be left.
                    os.unlink(tmpfile)
                except:
                    pass
