import os
import sys
import tty
import yaml
import sunhpc
import signal
import syslog
import traceback
import sunhpc.util
import sunhpc.error as error

from sunhpc.util import CommandError

from sunhpc.logs import Logs
slog = Logs(name="Sunhpc", show_time=True)

from sunhpc.util import getTerminalWidth

def _main(argv=None):
    try:
        database = None
    except ImportError:
        pass

    if len(argv) == 1:
        args = ['list', 'help']
    else:
        args = sys.argv[1:]

    module = None
    cmd = args[0].split()
    if len(cmd) > 1:
        s = 'sunhpc.commands.%s' % '.'.join(cmd)
        try:
            __import__(s)
            module = eval(s)
            i = 1
        except:
            module = None

    if not module:
        for i in range(len(args), 0, -1):
            s = 'sunhpc.commands.%s' % '.'.join(args[:i])
            try:
                __import__(s)
                module = eval(s)
                if module:
                    break
            except ImportError:
                #raise
                continue

    if not module:
        print ('error - invalid sunhpc command "%s"' % args[0])
        sys.exit(-1)

    name = ' '.join(s.split('.')[2:])

    try:
        command = getattr(module, 'Command')(database)
    except AttributeError:
        import sunhpc.commands.list.help
        help = sunhpc.commands.list.help.Command(database)
        fullmodpath = s.split('.')
        submodpath  = '/'.join(fullmodpath[2:])
        help.run({'subdir': submodpath}, [])
        print (help.getText())
        sys.exit(-1)

    if command.MustBeRoot and not (
        command.isRootUser() or command.isApacheUser()):
        os.system('sudo %s' % ' '.join(sys.argv))
    else:
        try:
            command.runWrapper(name, args[i:])
            text = command.getText()
            if len(text) > 0:
                if text.endswith('\n'):
                    sys.stdout.write(text)
                else:
                    print (text)
                print ()
        except CommandError as e:
            print (command.usage())
            print ('Error: ', e)
            #slog.info(command.usage())
            #slog.error(str(e))
            return 1

    config_file = '/etc/sunhpc/sunhpc.yaml' 
    if not os.path.exists(config_file):
        slog.error('=' * (getTerminalWidth() - 30))
        slog.error ('config file "%s" not found' % config_file)
        slog.info('Run following command to create the config file:')
        slog.info('    # sunhpc init config eth1')
        slog.error('=' * (getTerminalWidth() - 30))
    syslog.closelog()
    return 0

def main(argv=None):

    if any(flag in argv for flag in ['--debug', '-d']):
        _main(argv)
    else:
        try:
            return _main(argv)
        except KeyboardInterrupt:
            sys.stderr.write("\n")
            tty.error("Keyboard interrupt.")
            return signal.SIGINT.value

        except AttributeError as e:
            sys.stderr.write("\n")
            slog.error(str(e))
            return 1

        except SystemExit as e:
            return e.code

        except Exception as e:
            tty.error(e)
            return 3
