#!/usr/bin/env python3
# This file is placed in the Public Domain.
# pylint: disable=C0411,C0413,W0212,W0718,E0401


"main"


import getpass
import os
import sys


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


from genocide.config  import Config
from genocide.persist import Persist, skel
from genocide.errors  import errors, later
from genocide.main    import init, scan
from genocide.utils   import forever, pidfile, privileges


from genocide import modules


Cfg         = Config()
Cfg.name    = Config.__module__.split(".")[-2]
Cfg.mod     = "irc,rss"
Cfg.wdr     = os.path.expanduser(f"~/.{Cfg.name}")
Cfg.user    = getpass.getuser()
Cfg.pidfile = os.path.join(Cfg.wdr, f"{Cfg.name}.pid")


Persist.workdir = Cfg.wdr


def daemon(verbose=False):
    "switch to background."
    pid = os.fork()
    if pid != 0:
        os._exit(0)
    os.setsid()
    pid2 = os.fork()
    if pid2 != 0:
        os._exit(0)
    if not verbose:
        with open('/dev/null', 'r', encoding="utf-8") as sis:
            os.dup2(sis.fileno(), sys.stdin.fileno())
        with open('/dev/null', 'a+', encoding="utf-8") as sos:
            os.dup2(sos.fileno(), sys.stdout.fileno())
        with open('/dev/null', 'a+', encoding="utf-8") as ses:
            os.dup2(ses.fileno(), sys.stderr.fileno())
    os.umask(0)
    os.chdir("/")
    os.nice(10)


def wrap(func):
    "catch exceptions"
    try:
        func()
    except (KeyboardInterrupt, EOFError):
        print("")
    except Exception as ex:
        later(ex)
    errors()


def wrapped():
    "wrap main function"
    wrap(main)


def main():
    "main"
    daemon()
    privileges(Cfg.user)
    skel()
    pidfile(Cfg.pidfile)
    scan(Cfg.mod, modules)
    init(Cfg.mod, modules)
    forever()


if __name__ == "__main__":
    wrapped()
