#!/usr/bin/python -tt
# First Aid Kit - diagnostic and repair tool for Linux
# Copyright (C) 2007 Martin Sivak <msivak@redhat.com>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

import sys, getopt, os, pprint, logging
from threading import Thread
from pyfirstaidkit import Tasker
from pyfirstaidkit import Config
from pyfirstaidkit import reporting
from pyfirstaidkit import initLogger

class Flags:
    print_config = False
    main_help = False

class Output(Thread):
    def __init__(self, queue, importance = logging.INFO, *args, **kwargs):
        Thread.__init__(self, *args, **kwargs)
        self._running = True
        self._queue = queue
        self._importance = importance

    def run(self):
        levelstack = []

        while self._running:
            message = self._queue.get()

            if message["action"]==reporting.END:
                self._running = False
                continue
            elif message["action"]==reporting.QUESTION:
                print "FIXME: Questions not implemented yet"
            elif message["action"]==reporting.START:
                if self._importance<=message["importance"]:
                    print "START: %s (%s)" % (message["origin"].name, message["message"])
                levelstack.append(message["origin"].name)
            elif message["action"]==reporting.STOP:
                if self._importance<=message["importance"]:
                    print "STOP: %s (%s)" % (message["origin"].name, message["message"])
                if levelstack[-1]!=message["origin"].name:
                    print "WARNING: START/STOP ordering mismatch in stack: "+" / ".join(levelstack)
                else:
                    levelstack.pop()
            elif message["action"]==reporting.PROGRESS:
                if self._importance<=message["importance"]:
                    print "PROGRESS: %d of %d (%s)" % (message["message"][0], message["message"][1], message["origin"].name)
            elif message["action"]==reporting.INFO:
                if self._importance<=message["importance"]:
                    print "INFO: %s (%s)" % (message["message"], message["origin"].name)
            elif message["action"]==reporting.ALERT:
                if self._importance<=message["importance"]:
                    print "ALERT: %s (%s)" % (message["message"], message["origin"].name)
            elif message["action"]==reporting.EXCEPTION:
                print "EXCEPTION: %s (%s)" % (message["message"], message["origin"].name)
            elif message["action"]==reporting.TABLE:
                if self._importance<=message["importance"]:
                    print "TABLE %s FROM %s" % (message["title"], message["origin"].name,)
                    pprint.pprint(message["message"])
            elif message["action"]==reporting.TREE:
                if self._importance<=message["importance"]:
                    print "TREE %s FROM %s" % (message["title"], message["origin"].name,)
                    pprint.pprint(message["message"])
            else:
                print "FIXME: Unknown message action %d!!" % (message["action"],)
                print message

def usage(name):
    print """Usage:
 %s [params]
 %s [params] -a         - runs the automated default mode [diagnose]
 %s [params] -a <flow>  - runs the automated mode with specified flow
 %s [params] -a fix     - automated fixing sequence [using the fix flows]
 %s [params] -f <plugin> <flow>
 %s [params] -t <plugin> <task>
 params is none or more items from:
  -c <config file> - select different config file
  -r <root path>   - where is the root directory?
  -P <path>        - add different plugin path
                     it can be used more than once
  -v               - verbose mode
  -l <method>      - select different log method
  -x <plugin>      - exclude plugin from run
  -F <flag>        - set startup flag
  -g <gui>         - frontend to show results
  -h               - help
  --print-config   - print resulting config file
  --list           - list all plugins
  --info <plugin>  - get information about plugin
""" % (name, name, name, name, name, name)

if __name__=="__main__":
    try:
        params, rest = getopt.getopt(sys.argv[1:], "aftc:r:vl:x:F:g:P:h",
                ["list", "info=", "auto", "flow", "task", "config=", "root=",
                "verbose", "log=", "exclude=","flag=", "gui=", "plugin-path=",
                "print-config", "help"])
    except Exception, e:
        print "\nError parsing the argument line: ",e,"\n"
        usage(sys.argv)
        sys.exit(1)

    #
    # Preliminary checks before we parse the options.
    #
    if len(params) == 0:
        Flags.main_help = True

    for key,val in params:
        if key in ("-t", "--task"):
            Config.operation.mode = "task"
            Flags.main_help = False
        elif key in ("-a", "--auto"):
            Config.operation.mode = "auto"
            Flags.main_help = False
        elif key in ("-f", "--flow"):
            Config.operation.mode = "flow"
            Flags.main_help = False
        elif key in ("-c", "--config"):
            Config.read(val)
        elif key in ("-v", "--verbose"):
            Config.operation.verbose = "True"
        elif key in ("-l", "--log"):
            Config.log.method = val
        elif key in ("-x", "--exclude"):
            Config.plugin.disabled = Config.plugin.disabled + ' "%s"' % (val.encode("string-escape"))
            print "Excluding plugin %s\n" % (val,)
        elif key in ("-F", "--flag"):
            Config.operation.flags = Config.operation.flags + ' "%s"' % (val.encode("string-escape"))
        elif key in ("-r", "--root"):
            Config.system.root = val
        elif key in ("-g", "--gui"):
            Config.operation.gui = val
        elif key in ("-P", "--plugin-path"):
            if not os.path.isdir(val):
                print "%s is not a valid directory.  Exiting..."% val
                sys.exit(1)
            Config.set("paths", val.strip("/"), val)
        elif key in ("--print-config"):
            Flags.print_config = True
        elif key in ("-h", "--help"):
            Config.operation.help = "True"
            Flags.main_help = True
        elif key in ("--list"):
            Config.operation.mode = "list"
        elif key in ("--info"):
            Config.operation.mode = "info"
            Config.operation.params = val

    if Config.operation.mode == "flow":
        Config.operation.plugin = rest[0]
        if len(rest)<=1:
            Config.operation.mode = "plugin"
        else:
            Config.operation.flow = rest[1]
    elif Config.operation.mode == "auto":
        if len(rest)>0:
            Config.operation.mode = "auto-flow"
            Config.operation.flow = rest[0]
    elif Config.operation.mode == "task":
        Config.operation.plugin = rest[0]
        Config.operation.task = rest[1]

    if Flags.main_help:
        usage(sys.argv[0])
        sys.exit(1)

    if Flags.print_config:
        print 76*"-"
        Config.write(sys.stdout)
        print 76*"-"
        sys.exit(0)

    Config.lock()

    # Now that the config is locked, initialize log for plugin system.
    initLogger(Config)

    singlerun = Tasker(Config)

    if Config.operation.verbose=="False":
        outputThread = Output(singlerun.reporting())
    else:
        outputThread = Output(singlerun.reporting(), importance = 0)

    outputThread.start()

    try:
        singlerun.run()
    finally:
        singlerun.end()

    outputThread.join()


