"""
This script check if rsync is disable for disks full
and can send to graphite (by default) or list to stdout
"""
import sys
import socket
import time
import configparser
from oslo_config import cfg
from subprocess import Popen, PIPE

with open('/etc/rsyncd.conf') as f:
    file_content = '[globale]\n' + f.read()

default_cluster = socket.gethostname().split('.')[0].split('-')[0]
# Initialize script common oslo_config
CLI_OPTS = [
    cfg.StrOpt('server', short='s',
               help='Graphite server to send data'),
    cfg.IntOpt('port', default=2003, short='p',
               help='Graphite server port to send data'),
    cfg.StrOpt('cluster', default=default_cluster, short='c',
               help='Cluster name'),
    cfg.BoolOpt('list', short='l',
                help='List of disk with rsync disabled'),
]


def _prepare_config():
    """
    Prepare the oslo_config of scripts by analyse arguments
    return: the oslo_config object
    """
    CONF = cfg.ConfigOpts()
    CONF.register_cli_opts(CLI_OPTS)
    return CONF


def netcat(server, port, content):
    """
    Send data to graphite server
    """
    p = Popen(['/usr/bin/ncat', server, str(port)], stdin=PIPE)
    p.communicate(input=content.encode())


def print_list(disable):
    """
    Print a list of disk with rsync disable by type of server
    param disable: list of module rsync disable (ServerType_Disk)
    """
    disabled_disks = {}
    for k in disable:
        type, disk = k.strip().split('_')
        disabled_disks.setdefault(type, [])
        disabled_disks[type].append(disk)
    for k, v in disabled_disks.items():
        print(f"Rsync disks disable for type {k}:")
        for disk in v:
            print(f"\t{disk}")


def send_metric(args, disable):
    """
    Send metric to graphite
    param args: args of the script
    param disable: list of module rsync disable (ServerType_Disk)
    """
    if not args.server:
        print("Graphite server add ress not define")
        sys.exit(1)
    host = socket.gethostname().split('.')[0]
    date = time.time()
    netcat(args.server, args.port,
           f"{args.cluster}.{host}.rsync_disable {len(disable)} {date}\n")


def main():
    """
    Entry point for the script
    """

    args = _prepare_config()
    try:
        args(sys.argv[1:])
    except cfg.RequiredOptError as E:
        print(E)
        args.print_usage()
        return 1

    config_parser = configparser.RawConfigParser()
    config_parser.read_string(file_content)
    disable = [k for k, v in config_parser._sections.items() if k != 'globale'
               and int(v['max connections']) < 0]
    if args.list:
        print_list(disable)
    else:
        send_metric(args, disable)


if __name__ == "__main__":
    sys.exit(main())
