#!/usr/bin/env python

# It is assumed that the database to convert is
#    DiskMonitoringSummaryBackup
import MySQLdb
import datetime

if __name__ == '__main__':
    dbname_source = 'DiskMonitoringSummaryBackup'
    source_db = MySQLdb.connect('localhost', 'root', '', dbname_source)
    # dbname_target = 'DiskMonitoringSummary'
    # target_db = MySQLdb.connect('localhost', 'root', '', dbname_source)
    
    # DiskUsageHistoryWeekly conversion
    source_query = 'SELECT node, role, stage, dirname, sizes, counts, lifetime, day FROM DiskUsageHistoryWeekly'
    target_insert_template = """INSERT INTO DiskUsageHistoryWeekly(node, role, stage, dirname, sizes, counts, lifetime, week, status)
VALUES('%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s');"""
    source_cursor = source_db.cursor()
    source_cursor.execute(source_query)
    for (node, role, stage, dirname, sizes, counts, lifetime, day) in source_cursor.fetchall():
        date = datetime.datetime.strptime(str(day), "%Y-%m-%d")
        week_number = datetime.date(date.year, date.month, date.day).isocalendar()[1]
        week = '%d-%d' % (date.year, week_number)
        if role != 'deleted':
            target_insert = target_insert_template % (node, role, stage, dirname, sizes, counts, lifetime, week, 'undefined')
        else:
            target_insert = target_insert_template % (node, 'undefined', stage, dirname, sizes, counts, lifetime, week, 'deleted')
        print target_insert
