import os, shutil, re, sys
from subprocess import *

p = os.popen('rlog current_flr.txt')
    
target = sys.argv[1]
revs = []
for stuff in [i.strip() for i in p.read().split('----------------------------')]:
    if not stuff.startswith('revision'): continue
    lines = stuff.split('\n')
    revnum = lines[0].split(' ')[1]
    date = lines[1][6:lines[1].find(';')]
    message = '\n'.join(lines[2:])
    revs.append((revnum, date, message))
    if revnum == target: break

def diff(target):
    parts = revnum.split('.')
    oldnum = parts[0] + '.' + str(int(parts[1]) - 1)
    return os.popen('rcsdiff -r%s -r%s current_flr.txt' % (oldnum, revnum)).read()

if sys.argv[2] == 'init':
    if os.path.exists('new_flr.txt'): os.remove('new_flr.txt')
    if os.path.exists('new_flr.txt,v'): os.remove('new_flr.txt,v')

    shutil.copy('current_flr.txt,v', 'new_flr.txt,v')
    #os.chmod('new_flr.txt,v', 0666)

    for revnum, date, message in revs:
        assert not os.system('rcs -o%s new_flr.txt' % revnum)

    if len(sys.argv) > 3 and sys.argv[3] == '--apply':
        assert not os.system('co -l new_flr.txt')
        assert not os.system('co -p%s current_flr.txt > new_flr.txt' % target)
    else:
        assert not os.system('co -u new_flr.txt')
    print 'To replicate the original commit:'
    revnum, date, message = revs[-1]
    print 'ci -u -d"%s" -m"%s" new_flr.txt' % (date, message)

elif sys.argv[2] == 'commit':
    for revnum, date, message in revs[-2::-1]:
        print '- Applying ', message
        assert not os.system('co -f -l new_flr.txt')
        p = Popen(['patch', 'new_flr.txt'], stdin=PIPE)
        p.communicate(diff(revnum))
        if p.wait():
            rf = re.findall(re.compile('^- (.*)$', re.M), open('new_flr.txt.rej').read())
            print rf
            assert all(any(i.startswith(j) for j in ['Last', 'Highest', 'Current']) for i in rf)
            os.remove('new_flr.txt.rej')
        assert not os.system('ci -u -d"%s" -m"%s" new_flr.txt' % (date, message))

