"""
This script send replication progress to graphite
"""
from oslo_config import cfg
import sys, socket
import datetime
import time,random
from subprocess import Popen, PIPE, STDOUT

units={'h':3600,'m':60,'s':1}
default_cluster = socket.gethostname().split('.')[0].split('-')[0]
# Initialize script common oslo_config
CLI_OPTS = [           
    cfg.StrOpt('server', short='s', required=True,
               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'),
]

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 main():
    """
    Entry point for the script
    """
    args = _prepare_config()
    try:
        args(sys.argv[1:])
    except cfg.RequiredOptError as E:
        print(E)
        args.print_usage()
        sys.exit(1)
    line_log=''
    with open("/var/log/swift//object.log",'r') as file:
        for line in file:
            if line.endswith('remaining)\n'):
                line_log = line
    data = {}
    elems = line_log.split()
    try:
        date = datetime.datetime.strptime(
                        elems[0],'%Y-%m-%dT%H:%M:%S.%f%z').timestamp()
        name = elems[1]
        done,total = elems[3].split('/')
        data['parts_remaining'] = int(total) - int(done)
        data['duration'] = elems[8].split('.')[0]
        data['remaining'] = int(elems[10][:-1]) * units[elems[10][-1]]
        time.sleep(random.randint(0,59))
        for k,v in data.items():
            netcat(args.server,args.port, 
                f"{args.cluster}.{name}.replication.{k} {v} {date}\n")
    except:
        pass

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