#!/usr/bin/env python3
# This file is placed in the Public Domain.
# pylint: disable=C,I,R,W,E0402


__author__ = "B.H.J. Thate <thatebhj@gmail.com>"
__version__ = 1


import os
import readline
import sys
import termios
import time
import traceback


sys.path.insert(0, os.getcwd())


from genocide.clients import Client
from genocide.command import command
from genocide.errored import Errors
from genocide.loggers import Logging
from genocide.message import parse
from genocide.objects import update
from genocide.persist import Persist
from genocide.runtime import Cfg
from genocide.scanner import importer, scandir, scanpkg, starter, threader
from genocide.threads import launch


import genocide.modules


readline.redisplay()


Persist.workdir = os.path.expanduser("~/.%s" % Cfg.name)


date = time.ctime(time.time()).replace('  ', ' ')


def cprint(txt):
    if "v" in Cfg.opts:
        print(txt)
        sys.stdout.flush()


Logging.raw = cprint


class CLI(Client):

    def announce(self, txt):
        pass

    def raw(self, txt):
        print(txt)
        sys.stdout.flush()


class Console(CLI):

    def handle(self, evt):
        CLI.handle(self, evt)
        evt.wait()

    def poll(self):
        return self.event(input("> "))


def daemon():
    pid = os.fork()
    if pid != 0:
        os._exit(0)
    os.setsid()
    os.umask(0)
    sis = open('/dev/null', 'r')
    os.dup2(sis.fileno(), sys.stdin.fileno())
    sos = open('/dev/null', 'a+')
    ses = open('/dev/null', 'a+')
    os.dup2(sos.fileno(), sys.stdout.fileno())
    os.dup2(ses.fileno(), sys.stderr.fileno())


def waiter():
    got = []
    for ex in Errors.errors:
        traceback.print_exception(type(ex), ex, ex.__traceback__)
        got.append(ex)
    for exc in got:
        Errors.errors.remove(exc)


def wrap(func):
    fds = sys.stdin.fileno()
    gotterm = True
    try:
        old = termios.tcgetattr(fds)
    except termios.error:
        gotterm = False
    try:
        func()
    except (EOFError, KeyboardInterrupt):
        print('')
    finally:
        if gotterm:
            termios.tcsetattr(fds, termios.TCSADRAIN, old)
        waiter()


def main():
    dowait = False
    cfg = parse(' '.join(sys.argv[1:]))
    update(Cfg, cfg)
    if "c" in cfg.opts:
        print(f'{Cfg.name.upper()} started {date} mod={Cfg.mod}')
    if os.path.exists("mod"):
        scandir("mod", importer, Cfg.mod)
    scanpkg(genocide.modules, importer, Cfg.mod, threader)
    if cfg.txt:
        cli = CLI()
        command(cli, cfg.otxt)
    elif 'd' in cfg.opts:
        daemon()
        dowait = True
    elif 'c' in cfg.opts:
        dowait = True
    if dowait:
        if "c" in cfg.opts:
            csl = Console()
            launch(csl.loop)
        while 1:
            time.sleep(1.0)
            waiter()


wrap(main)
waiter()
