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


"daemon"


import getpass
import os
import sys


from nixt.config  import config
from nixt.main    import init, scan, wrap
from nixt.utils   import forever, pidfile, privileges


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 main():
    "main"
    daemon()
    cfg = config()
    cfg.mod  = "cmd,err,irc,rss,thr"
    cfg.user = getpass.getuser()
    privileges(cfg.user)
    pidfile(cfg.pidfile)
    from nixt.modules import all as modules
    scan(cfg.mod, modules)
    init(cfg.mod, modules)
    forever()


if __name__ == "__main__":
    wrap(main)
    os._exit(0)
