#!/usr/bin/env python

import mitsfs
from psycopg2 import connect
from mitsfs.db import easyCursor

db = connect('dbname=mitsfs')

db.rollback()
c = db.cursor(cursor_factory=easyCursor)

client = 'fixdex.py'
c.execute('select set_client(%s)', (client,))

c.execute("""select * from log where username like 'kevinr' and client like 'SQL' and generation <= 120157 order by generation;""")

import re
format_re = re.compile('UPDATE book\nshelfcode_id 1\n(\d+)\nshelfcode_id 1\n564420')

count = 0
#oldest_generation = 0
changes = []

for (generation, obj_id, stamp, username, ip, client, relid, change) in c:
    result = re.match(format_re, change)
    if result:
        changes.append("update book set shelfcode_id=" + result.group(1) + " where book_id=" + str(obj_id) + ";")
        count += 1
#        oldest_generation = generation
    else:
        print "-- ERROR: DOESN'T MATCH: " + str(x)

for change in changes:
    c.execute(change)

print "count: " + str(count)
print "generation: " + str(generation)

print

if mitsfs.readyes("Commit changes? "):
    print "Committing!"
    db.commit()

db.rollback()
