#!/usr/bin/env python3

import socket
import time
import os
import argparse
import logging

from contextlib import closing


def parse_arguments():
    parser = argparse.ArgumentParser(description='watchdog notification test')
    parser.add_argument('--bad', action='store_true', help='bad mode')
    return parser.parse_args()


def main(opts):
    notify_addr = os.getenv('NOTIFY_SOCKET')
    if not notify_addr:
        raise RuntimeError('NOTIFY_SOCKET not set')

    watchdog_usec = os.getenv('WATCHDOG_USEC')
    if not watchdog_usec:
        raise RuntimeError('WATCHDOG_USEC not set')

    # convert to seconds
    watchdog_timeout = int(watchdog_usec) / 1000000

    logging.info('watchdog timeout: %us', watchdog_timeout)
    logging.info('notification socket address: %s', notify_addr)

    if notify_addr.startswith('@'):
        # abstract socket address is represented by a bytes-like object, with
        # an initial null byte
        notify_addr = notify_addr.encode().replace(b'@', b'\x00')

    if opts.bad:
        sleep_time = 2 * watchdog_timeout
        logging.warning('running in "bad" mode')
    else:
        sleep_time = watchdog_timeout / 2

    logging.info('watchdog notification every %ss', sleep_time)

    with closing(socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)) as sock:
        sock.connect(notify_addr)

        while True:
            logging.info('watchdog kick')
            sock.sendall(b'WATCHDOG=1')
            time.sleep(sleep_time)


if __name__ == '__main__':
    opts = parse_arguments()
    logging.basicConfig(level=logging.DEBUG)
    main(opts)
