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


"feeds rss"


import getpass
import inspect
import os
import pwd
import sys
import termios
import time
import _thread


from rssbot import Client, Command, Default, Error, Event, Object, Storage
from rssbot import cdir, debug, launch, parse_command, spl


Cfg         = Default()
Cfg.mod     = "cmd,irc,mod,pwd,rss"
Cfg.name    = "rssbot"
Cfg.wd      = os.path.expanduser(f"~/.{Cfg.name}")
Cfg.pidfile = os.path.join(Cfg.wd, f"{Cfg.name}.pid")
Cfg.user    = getpass.getuser()
Storage.wd  = Cfg.wd


from rssbot import modules


def cmnd(txt):
    evn = Event()
    evn.txt = txt
    Command.handle(evn)
    evn.wait()
    for txt in evn.result:
        print(txt)
    return evn


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


def scan(pkg, modstr, initer=False, wait=True) -> []:
    mds = []
    for modname in spl(modstr):
        module = getattr(pkg, modname, None)
        if not module:
            continue
        for _key, cmd in inspect.getmembers(module, inspect.isfunction):
            if 'event' in cmd.__code__.co_varnames:
                Command.add(cmd)
        for _key, clz in inspect.getmembers(module, inspect.isclass):
            if not issubclass(clz, Object):
                continue
            Storage.add(clz)
        if initer and "init" in dir(module):
            module._thr = launch(module.init, name=f"init {modname}")
            mds.append(module)
    if wait and initer:
        for mod in mds:
            mod._thr.join()
    return mds


def main():
    Storage.skel()
    parse_command(Cfg, " ".join(sys.argv[1:]))
    if not Cfg.otxt:
       return
    privileges(Cfg.user)
    scan(modules, Cfg.mod)
    cmnd(Cfg.otxt)


main()
