#!/usr/bin/python

import sys
import os
import os.path
import optparse 
import commands
import filecmp


usage="""
%prog [options] [file+]'

Tool to resolves configuration files ending in .rpmsave, .rpmnew, or .rpmorig.
It uses /etc/init.d/rpmconfigcheck to find out about such files.
It will open vi -d <old> <new>, and offer actions afterwards.

If called without arguments, it will pick a file and offer to resolve the differences.

"""

editor = os.getenv('EDITOR', default='vim')


def listing():
    r = commands.getoutput('/etc/init.d/rpmconfigcheck')
    r = [ r.strip() for r in r.splitlines() if r.startswith(' ') ]
    return r


def resolve(f):
    print f

    otherf = os.path.splitext(f)[0]
    print otherf

    if not os.path.exists(f):
        sys.exit('file %s does not exist' % f)
    if not os.path.exists(otherf):
        sys.exit('file %s does not exist' % otherfile)


    # are they the same anyway?
    if filecmp.cmp(f, otherf):

        print 'files are identical, nothing to do... except:'
        print '  d) delete %s' % f
        if f.endswith('rpmnew'):
            print '  r) replace %s with %s' % (otherf, f)
        print '  s) skip'

        input = raw_input('Your choice? ')
        if input in 'd':
            print 'unlinking', f
            os.unlink(f)
        elif input in 'r':
            print 'replacing', otherf
            os.rename(f, otherf)

    else: 
        # they differ

        if f.endswith('rpmsave') or f.endswith('rpmorig'):

            os.system('%s -d %s %s' % (editor, f, otherf))
            print 'after merging, choose one of these alternatives:'
            print
            print '  d) delete %s' % f
            print '  r) replace %s with %s' % (otherf, f)
            print '  s) skip'
            print

            input = raw_input('Your choice? ')
            if input in 'd':
                print 'unlinking', f
                os.unlink(f)
            elif input in 'r':
                print 'replacing', otherf
                os.rename(f, otherf)


        elif f.endswith('rpmnew'):

            if os.path.getmtime(f) < os.path.getmtime(otherf):
                print 'Warning: .rpmnew file is OLDER'
                input = raw_input('Press ENTER to continue ')
            
            os.system('%s -d %s %s' % (editor, otherf, f))
            print 'after merging, choose one of these alternatives:'
            print
            print '  d) delete %s' % f
            print '  r) replace %s with %s' % (otherf, f)
            print '  s) skip'
            print

            input = raw_input('Your choice? ')
            if input in 'd':
                print 'unlinking', f
                os.unlink(f)
            elif input in 'r':
                print 'replacing', otherf
                os.rename(f, otherf)


def main():

    parser = optparse.OptionParser(usage=usage, version="%prog 1.0")

    parser.add_option("-l", "--list",
                      dest="listing",
                      default=False,
                      action="store_true",
                      help="list files")

    parser.add_option("-a", "--all",
                      dest="all",
                      default=False,
                      action="store_true",
                      help="loop through all found files")

    (options, args) = parser.parse_args()


    try:
        if options.listing:
            print '\n'.join(listing())
            sys.exit(0)

        if options.all:
            args = listing()

        if args:
            for arg in args:

                # sanity check:
                ext = os.path.splitext(arg)[1]
                if not ext in ['.rpmorig', '.rpmnew', '.rpmsave']:
                    sys.exit('cannot handle files ending in \'%s\'' % ext)

                # sanity check:
                if not os.path.exists(arg):
                    sys.exit('file %s does not exist' % arg)
                    
                resolve(arg)

        else:
            files = listing()
            if len(files):
                resolve(files[0])
            else:
                print 'nothing to do!'
                sys.exit(0)

    except KeyboardInterrupt:
        sys.exit('^C')




if __name__ == '__main__': main()
