#!/opt/vertica/oss/python/bin/python
from __future__ import absolute_import

import sys
import pwd
import os
import threading

from vertica.network import adapterpool
from vertica.utils.vthread import VThread

from vertica.tools.Scrutinize.ScrutinArgs import ScrutinArgs
from vertica.tools.Scrutinize.ScrutinConfig import ScrutinConfig
from vertica.tools.Scrutinize.ScrutinWorker import ScrutinWorker
from vertica.tools.Scrutinize.Scrutinize import Scrutinize
from vertica.tools.Scrutinize.ThreadMonitor import ThreadMonitor

def main():
    """ Run Scrutinize """

    valid_user_name_or_die()

    arg_parser = ScrutinArgs()

    status = arg_parser.parse_and_validate(sys.argv)
    if status != 0:
        sys.exit(status)

    if arg_parser.options.worker_instructions:
        print "Invoking worker on %s" % arg_parser.options.worker_instructions
        print arg_parser.get_version()
        if arg_parser.options.just_task_name:
            print "Running task %s " % arg_parser.options.just_task_name
        else:
            print "Running all tasks"
        worker = ScrutinWorker(
            arg_parser.options.worker_instructions
        )
        worker.run(arg_parser.options.just_task_name)
        sys.exit(0)

    print arg_parser.get_version()
    config = ScrutinConfig()

    try:
        # this method raises errors if options not valid
        config.process_options(arg_parser)
    except Exception as e:
        print "\n\nError: Failed to configure Scrutinize."
        print e
        sys.exit(1)

    try:
        diags = Scrutinize(config)
        diags.prepare_collection()
    except Exception as e:
        print "\n\nFailed to initialize Scrutinize."
        print e
        sys.exit(1)

    try:
        diags.scrutinizeAll()
    except Exception as e:
        print ("Exception caught during scrutinize diagnostic collection.\n"
               "The exception message is\n{m}.\n"
               "Please check the most recent scrutinize logs in "
               "/opt/vertica/log/".format(m=e))
        cleanup()
        sys.exit(12)
    # Everything was OK, cleanup and exit cleanly
    cleanup()
    sys.exit(0)


def valid_user_name_or_die():
    # XXX(DR): Ideally we should only allow dbadmin to invoke scrutinize. This
    # is already handled by admintools, but not in a way that is very nice to
    # try to use. This is an improvement, so feel free to keep it as-is. But
    # consider refactoring the mess of isOkToRun() to use
    # Configurator.get_dbadmin_username() or something like that.

    # check userName
    username = pwd.getpwuid(os.getuid())[0]
    if (username == "root"):
       print "\nRoot user is not allowed to use this tool."
       print "Try again as the DB administrative user."
       sys.exit(1)

def cleanup():
    """Cleans up any potentially leftover items

    SSH connections and Threads
    """

    for thread in threading.enumerate():
        if (isinstance(thread, VThread) or
            isinstance(thread, ThreadMonitor)):
            print ("Cleanup: Found a thread generated "
                   "by Scrutinize %s" % thread.name)
            print "Cleanup: Canceling thread %s" % thread.name
            thread.cancel()

if __name__ == "__main__":
    main()
