#!/usr/bin/python
import MySQLdb, sys
if len(sys.argv) <= 2:
    sys.exit(
        "Two arguments required. Example: %s <template_user> <destination_user>"
        % (sys.argv[0]))

template_user = sys.argv[1]
destination_user = sys.argv[2]
connection = MySQLdb.connect(host="localhost",
                             user="root",
                             passwd="",
                             db="merlin")
cursor = connection.cursor()

# delete all existing dashboards and dashboard widgets for dstusercursor.
execute("SELECT id FROM dashboards where username = %s", (destination_user))
for row in cursor.fetchall():
    cursor.execute("DELETE FROM dashboard_widgets WHERE dashboard_id = '%s'" %
                   (row))
    cursor.execute("DELETE FROM dashboards WHERE username = %s",
                   (destination_user))

# get all dashboards for srcusercursor.
execute("SELECT id, name, layout from dashboards where username = %s",
        (template_user))
srcuser_dashboards = cursor.fetchall()

# clone dashboards from src to dst user and get dashboard ids
dstuser_dashboards = []
for row in srcuser_dashboards:
    id, name, layout = row
    print "Cloning dashboard %s to user %s" % (name, destination_user)
    cursor.execute(
        "INSERT INTO dashboards (name, layout, username) VALUES (%s, %s, %s)",
        (name, layout, destination_user))
    dstuser_dashboards.append(cursor.lastrowid)
    for src_dashboard in srcuser_dashboards:
        src_id, src_name, src_layout = src_dashboard
        print "Source: %s" % (src_id)
        cursor.execute(
            "SELECT id, name, position, setting FROM dashboard_widgets WHERE dashboard_id = '%s'",
            src_id)
        src_widgets = cursor.fetchall()
    for dst_dashboard in dstuser_dashboards:
        print "\t Adding: %s" % (dst_dashboard)
        cursor.execute(
            "INSERT INTO dashboard_widgets (dashboard_id, name, position, setting) SELECT %s, name, position, setting FROM dashboard_widgets WHERE dashboard_id = '%s'"
            % (dst_dashboard, src_id))
        dstuser_dashboards.remove(dst_dashboard)
