#!/usr/bin/env python

"""
Sync a Durus SQLite database to a backup.
"""

import sys

import apsw
def mytrace(statement, bindings):
    "Called just before executing each statement"
    print "SQL:",statement
    if bindings:
        print "Bindings:",bindings
    return True  # if you return False then execution is aborted


from_db = sys.argv[1]
to_db = sys.argv[2]

con = apsw.Connection(from_db)
cur = con.cursor()
#cur.setexectrace(mytrace)


cur.execute("ATTACH '%s' AS to_db" % to_db)
cur.execute("BEGIN")


# check the most recent trans in TO_DB
max_trans_id = cur.execute("SELECT MAX(trans_id) FROM to_db.trans_history").next()[0]
last_trans_id = cur.execute("SELECT MAX(trans_id) FROM trans_history").next()[0]

min_trans_id = cur.execute("SELECT MIN(trans_id) FROM to_db.trans_history").next()[0]
earliest_trans_id = cur.execute("SELECT MIN(trans_id) FROM trans_history").next()[0]

if min_trans_id < earliest_trans_id:
    # the source has been packed, need to copy it.
    print "Source database has been packed, full copy needed."
    cur.execute("ROLLBACK")
else:    
    if last_trans_id > max_trans_id:
        print "Need sync:"
        print "'%s' - [%d] more recent than '%s' - [%d]" % (from_db, last_trans_id, to_db,
                max_trans_id)

        # copy all records with a trans_id greater than the max into to_db
        
        cur.execute("INSERT OR REPLACE INTO to_db.records SELECT * FROM records WHERE records.trans_id > ?", (max_trans_id,))
        cur.execute("INSERT OR REPLACE INTO to_db.trans_history SELECT * FROM trans_history WHERE trans_history.trans_id > ?", (max_trans_id,))
        cur.execute("COMMIT")
        
    elif last_trans_id < max_trans_id:
        print "Possible error in choice of databases:"
        print "'%s' - [%d] older than '%s' - [%d]" % (from_db, last_trans_id,
                to_db, max_trans_id)
    else:
        print "No need for sync:"
        print "'%s' - [%d] the same as '%s' - [%d]" % (from_db, last_trans_id,
                to_db, max_trans_id)
        cur.execute("ROLLBACK")
