#!/usr/bin/env python
"""
Commands for initializing the proper database tables
or cleaning the database.
"""
from __future__ import print_function

from builtins import input

__revision__ = "$Id: wmcore-db-init,v 1.10 2010/07/05 03:05:32 meloam Exp $"
__version__ = "$Revision: 1.10 $"
__author__ = "fvlingen@caltech.edu"

import getopt
import logging
import os
import sys
import time

logging.basicConfig(level=logging.DEBUG)

from WMCore.Configuration import loadConfigurationFile
from WMCore.WMFactory import WMFactory
from WMCore.WMInit import WMInit
from sqlalchemy.engine.url import make_url

def usage():

    msg = """
Usage: wmcore-db-init [--config] (--create|--destroy) <options>

You must either set the WMAGENT_CONFIG environment variable or specify the config file with
--config 

options
--modules= comma separated list of modules whose tables
need to be created.
"""
    print(msg)


valid = ['config=', 'create', 'destroy', 'modules=']

try:
    opts, args = getopt.getopt(sys.argv[1:], "", valid)
except getopt.GetoptError as ex:
    print(str(ex))
    usage()
    sys.exit(1)

config = None
command = None
modules = []

for opt, arg in opts:
    if opt == "--create":
        if command != None:
            msg = "Command specified twice:\n"
            msg += usage()
            print(msg)
            sys.exit(1)
        command = "create"
    if opt == "--destroy":
        if command != None:
            msg = "Command specified twice:\n"
            msg += usage()
            print(msg)
            sys.exit(1)
        command = "destroy"
    if opt == "--modules":
        modules = arg.split(',')
    if opt == "--config":
        config = arg

if command == None:
    msg = "No command specified\n"
    print(msg)
    usage()
    sys.exit(0)

if config == None:
    config = os.environ.get("WMAGENT_CONFIG", None)

    if config == None:
        msg = "No Config file provided\n"
        msg += "provide one with the --config option"
        print(msg)
        usage()
        sys.exit(1)

if not os.path.exists(config):
    print("Can't find config: %s" % config)
    sys.exit(1)

# load the config file here.
cfgObject = loadConfigurationFile(config)

wmInit = WMInit()

def connectionTest(config):
    """
    _connectionTest_

    Create a DB Connection instance to test the connection specified
    in the config file.

    """
    print('checking default database connection')

    (dialect, junk) = config.CoreDatabase.connectUrl.split(":", 1)
    socket = getattr(config.CoreDatabase, "socket", None)

    try:
       wmInit.setLogging('wmcoreD', 'wmcoreD', logExists = False, logLevel = logging.DEBUG)
       wmInit.setDatabaseConnection(dbConfig = config.CoreDatabase.connectUrl,
                                    dialect = dialect,
                                    socketLoc = socket)
    except Exception as ex:
        msg = "Unable to make connection to using \n"
        msg += "parameters provided in %s\n" % config.CoreDatabase.connectUrl
        msg += str(ex)
        print(msg)
        raise ex
    print('default database connection tested')

def create(config):
    params = {}

    if hasattr(config.CoreDatabase, "tablespaceName"):
        params["tablespace_table"] = config.CoreDatabase.tablespaceName
    if hasattr(config.CoreDatabase, "indexspaceName"):
        params["tablespace_index"] = config.CoreDatabase.indexspaceName

    wmInit.setSchema(modules, params = params)
    return

def destroy(config):
    wmInit.clearDatabase()
    return

def executeCommand(command):
    stdin,stdout,stderr = os.popen3(command)
    for x in [stdout, stderr]:
        line = x.read()
        while line:
            print(line)
            line = x.read()

def askConfirmation():
    while True:
        msg = "Are you sure you want to delete all the database? The operation is NOT reversible. (yes, no)"
        print(msg)
        answer = input()
        if answer.upper() in ['YES', 'NO']:
            return answer

if command == "create":
    connectionTest(cfgObject)
    create(cfgObject)
    sys.exit(0)
if command == "destroy":
    answer = askConfirmation()
    if answer.upper() == 'YES':
        connectionTest(cfgObject)
        destroy(cfgObject)
        sys.exit(0)
    else:
        print("Exiting without doing anything")

