#!/usr/bin/python -W ignore::DeprecationWarning
#
# archipel-updatedomain
#
# Copyright (C) 2010 Antoine Mercadal <antoine.mercadal@inframonde.eu>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import os
import sqlite3
import sys
from optparse import OptionParser
import commands


def update(dbfile, newdomain):
    db = sqlite3.connect(dbfile)
    c = db.cursor()
    c.execute("select * from virtualmachines")

    for vm in c:
        jid, password, date, comment, name = vm
        newjid = jid.split("@")[0] + "@" + newdomain
        db.execute("UPDATE virtualmachines SET jid='%s' WHERE jid='%s'" % (newjid, jid))
    db.commit()
    print "\033[32mSUCCESS: domain has been updated to %s in file %s\033[0m" % (newdomain, dbfile)


if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-f", "--file",
                        dest="dbfile",
                        help="the sqlite3 file of hypervisor",
                        metavar="FILE",
                        default="/var/lib/archipel/hypervisor.sqlite3")
    parser.add_option("-d", "--domain",
                        dest="domain",
                        help="the new domain to use",
                        metavar="DOMAIN")
    options, args = parser.parse_args()

    for p in ("/var/lock/subsys/archipel", "/var/lock/archipel", "/tmp/.lock-archipel"):
        if os.path.exists(p):
            print "\033[31mERROR: Archipel is running. please stop it before running this script\n\033[0m"
            sys.exit(1)

    if not options.dbfile or not options.domain :
        parser.error("you must enter a FILE and a DOMAIN. see --help for help")
        sys.exit(1)

    if not os.path.exists(options.dbfile):
        parser.error("database %s doesn't exist" % options.dbfile)
        sys.exit(1)

    update(options.dbfile, options.domain)
