#!/usr/bin/env python3
# This file is placed in the Public Domain.

__version__ = 43

import atexit
import os
import sys
import termios

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

from bot.bus import first
from bot.clt import Client
from bot.krn import Kernel, kcmd
from bot.obj import cfg

import bot.all
import gcd.all

all = "adm,cms,fnd,irc,krn,log,rss,tdo,trt,req,sui,wsd,ver"
name = "gcd"
resume = {}

def termsetup(fd):
    return termios.tcgetattr(fd)

def termreset():
    if "old" in resume:
        try:
            termios.tcsetattr(resume["fd"], termios.TCSADRAIN, resume["old"])
        except termios.error:
            pass

def termsave():
    try:
        resume["fd"] = sys.stdin.fileno()
        resume["old"] = termsetup(sys.stdin.fileno())
        atexit.register(termreset)
    except termios.error:
        pass

class CLI(Client):

    def raw(self, txt):
        print(txt)

    def start(self):
        super().start()
        self.initialize(kcmd)

class Console(CLI):

    def handle(self, e):
        super().handle(e)
        e.wait()

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

def main():
    cfg.wd = os.path.expanduser("~/.%s" % name)
    k = Kernel()
    k.parse()
    k.boot(name, __version__)
    if k.cfg.txt:
        k.regs(all)
        c = CLI()
        c.initialize()
        e = c.event(k.cfg.otxt)
        kcmd(c, e)
        e.wait()
        return
    c = Client()
    if k.opts("c"):
        c = Console()
        k.cfg.mods += "adm,cms,sui,trt,req,wsd"
    k.regs(k.cfg.mods)
    k.init(k.cfg.mods)
    if k.opts("cd"):
        c.start()
        c.wait()

def exec(main):
    termsave()
    try:
        main()
    except PermissionError as ex:
        print(str(ex))
    except KeyboardInterrupt:
        pass
    finally:
        termreset()

exec(main)
