#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Univention Reload Service
#  restart services centrally for rate limiting
#
# Copyright 2016-2023 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

from errno import ENOENT
from os import umask, unlink
from socket import AF_UNIX, SOCK_DGRAM, socket, timeout
from subprocess import call
from sys import stdout
from time import monotonic, strftime

RECV_BUFFER_SIZE = 128
RELOAD_SOCKET_PATH = "/var/run/univention-reload-service.socket"


def timestamp():
    return strftime("%Y-%m-%d %H:%M:%S%z")


def log(message):
    stdout.write("%s %s\n" % (timestamp(), message))
    stdout.flush()


def reload_squid():
    log("Reloading %r now" % (reload_squid.name,))
    reload_squid.last = monotonic()
    call(("/bin/systemctl", "reload", "squid"))  # nosec


reload_squid.name = "squid"
reload_squid.delay = 15.0
reload_squid.last = float("-inf")

QUEUE = {}  # reloader → when-to-reload


def queue(reloader):
    now = monotonic()
    if reloader not in QUEUE:
        when = max(reloader.last + reloader.delay, now)
        log("Reloading %r in %f s" % (reloader.name, when - now))
        QUEUE[reloader] = when


def process_queue():
    now = monotonic()
    for reloader, when in list(QUEUE.items()):
        if when <= now:
            reloader()
            del QUEUE[reloader]


def handle(message):
    message = tuple(message.split(" "))
    if message == ("reload", "squid"):
        queue(reload_squid)
    else:
        log("Command not implemented %r!" % (message,))


def time_to_next():
    if not QUEUE:
        return None  # no timeout
    now = monotonic()
    next = min(QUEUE.values())
    return max(next - now, 0.1)  # minimal delay 100 ms to not busy-wait


def create_socket(socket_path):
    try:
        unlink(socket_path)
    except OSError as oserror:
        if oserror.errno != ENOENT:
            raise
    sock = socket(AF_UNIX, SOCK_DGRAM)
    oldmask = umask(0o177)  # create the socket as srw-------, so that only root can access it
    try:
        sock.bind(socket_path)
    finally:
        umask(oldmask)
    return sock


def main():
    log("Starting")
    sock = create_socket(RELOAD_SOCKET_PATH)
    while True:
        process_queue()
        sock.settimeout(time_to_next())
        try:
            message = sock.recv(RECV_BUFFER_SIZE)
        except timeout:
            pass
        else:
            handle(message.decode("UTF-8", "ignore"))


if __name__ == "__main__":
    main()
