#!/usr/bin/env python3
# This file is placed in the Public Domain.
#
# pylint: disable=C,R,W0105,E0401
# ruff: noqa: E402


"""botl <cmd> [key=val] [key==val]

use the cmd command to see a list of comands."""


"cli"


import getpass
import os
import pwd
import readline # pylint: disable=W0611
import sys
import time


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


from botl.client  import Client, cmnd, parse_cmd, spl
from botl.command import Command
from botl.default import Default
from botl.errors  import debug, enable, errors
from botl.runtime import broker
from botl.workdir import Workdir, skel


from botl import modules


if os.path.exists("mods"):
    import mods
else:
    mods = None


Cfg             = Default()
Cfg.mod         = "cmd,mod"
Cfg.opts        = ""
Cfg.name        = "botl"
Cfg.version     = "552"
Cfg.user        = getpass.getuser()
Cfg.wd          = os.path.expanduser(f"~/.{Cfg.name}")
Cfg.pidfile     = os.path.join(Cfg.wd, f"{Cfg.name}.pid")
Workdir.workdir = Cfg.wd


dte = time.ctime(time.time()).replace("  ", " ")


class CLI(Client):

    def __init__(self):
        Client.__init__(self)
        broker.add(self)

    def announce(self, txt):
        pass

    def say(self, _channel, txt):
        txt = txt.encode('utf-8', 'replace').decode()
        print(txt)


def init(pkg, modstr):
    mds = []
    for modname in spl(modstr):
        module = getattr(pkg, modname, None)
        if not module:
            continue
        if "init" in dir(module):
            module.init()
            mds.append(module)
    return mds


def privileges(username):
    pwnam = pwd.getpwnam(username)
    os.setgid(pwnam.pw_gid)
    os.setuid(pwnam.pw_uid)


def ver(event):
    event.reply(f"{Cfg.name.upper()} {Cfg.version}")


def main():
    Command.add(ver)
    enable(print)
    privileges(Cfg.user)
    skel()
    parse_cmd(Cfg, " ".join(sys.argv[1:]))
    if 'a' in Cfg.opts:
        Cfg.mod = ",".join(modules.__dir__())
        if mods:
            Cfg.mod += "," + ",".join(mods.__dir__())
    if "v" in Cfg.opts:
        debug(f"{Cfg.name.upper()} {Cfg.opts.upper()} started {dte}")
    if "h" in Cfg.opts:
        print(__doc__)
        return
    return cmnd(Cfg.otxt, print)


if __name__ == "__main__":
    main()
    errors()
