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


"daemon"


import getpass
import os
import pathlib
import pwd
import sys
import time


from otpcr.client  import init, scan
from otpcr.default import Default
from otpcr.disk    import Workdir


from otpcr import modules


Cfg             = Default()
Cfg.dis         = ""
Cfg.mod         = "cmd,err,irc,log,mod,req,rss,tdo,thr,tmr"
Cfg.opts        = ""
Cfg.name        = "otpcr"
Cfg.version     = "21"
Cfg.wdr         = os.path.expanduser(f"~/.{Cfg.name}")
Cfg.pidfile     = os.path.join(Cfg.wdr, f"{Cfg.name}.pid")


Workdir.workdir = Cfg.wdr


def daemon(pidfile, verbose=False):
    "switch to background."
    pid = os.fork()
    if pid != 0:
        os._exit(0) # pylint: disable=W0212
    os.setsid()
    pid2 = os.fork()
    if pid2 != 0:
        os._exit(0) # pylint: disable=W0212
    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("/")
    if os.path.exists(pidfile):
        os.unlink(pidfile)
    path = pathlib.Path(pidfile)
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(pidfile, "w", encoding="utf-8") as fds:
        fds.write(str(os.getpid()))


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


def main():
    "main"
    Workdir.skel()
    Cfg.user = getpass.getuser()
    Cfg.mod  = ",".join(dir(modules))
    daemon(Cfg.pidfile, "-v" in sys.argv)
    privileges(Cfg.user)
    scan(modules, Cfg.mod)
    init(modules, Cfg.mod)
    while 1:
        time.sleep(1.0)


main()
