"""check_gridstorage - Attempts to read, write, and list files in grid storage."""

import os
import datetime
import time
from typing import List
from arcnagios import vomsutils
from arcnagios.arcutils import ArcClient
from arcnagios.nagutils import NagiosPlugin, OK, CRITICAL, UNKNOWN, \
                               ServiceCritical, ServiceReport
from arcnagios.confargparse import UsageError
from arcnagios.utils import log_process_error

class Check_gridstorage(NagiosPlugin, vomsutils.NagiosPluginVomsMixin):
    # pylint: disable=super-init-not-called,invalid-name

    main_config_section = ['gridstorage']

    def __init__(self):
        NagiosPlugin.__init__(self, use_host = True, use_port = True)
        self.arcclient = None
        argp = self.argparser.add_argument_group('Probe-Specific Options')
        argp.add_argument('--url', dest = 'url',
                help = 'The remote URL on which to perform the tests.')
        argp.add_argument('--write-url', dest = 'write_url',
                help = 'The URL for the initial write operation if different '
                       'from the other URLs.  This is primarily used for LFC.')
        argp.add_argument('--dir-url', dest = 'dir_url',
                help = 'The URL of the directory holding the test file. '
                       'A file name including the host name and a time stamp '
                       'will be appended. This option is only useful if you '
                       'enable write operations, and it will not work '
                       'correctly for LFC.')
        argp.add_argument('--disable-read', dest = 'enable_read',
                default = True, action = 'store_false',
                help = 'Disable the read check on the the URL.')
        argp.add_argument('--disable-list', dest = 'enable_list',
                default = True, action = 'store_false',
                help = 'Disable the list check on the the URL.')
        argp.add_argument('--list-dir', dest = 'list_dir',
                default = False, action = 'store_true',
                help = 'List the URL of the directory containing the file '
                       'rather than the file itself.  This will use '
                       '--dir-url if provided, otherwise it will use --url '
                       'after stripping the last component.')
        argp.add_argument('--enable-write', dest = 'enable_write',
                default = False, action = 'store_true',
                help = 'Enable write and delete operations on the url. '
                       'If enabled a file with a fairly unique content will '
                       'be written before any list and read operations, '
                       'and the file will be deleted after.')
        argp.add_argument('-t', '--timeout', dest = 'timeout',
                type = int, default = 120,
                help = 'Timeout.  This is divided among the sub-tasks, so '
                       'individual operations will get shorter times to '
                       'complete.  The minimum value is 5 seconds.')
        argp.add_argument('--granular-perfdata', dest = 'granular_perfdata',
                default = False, action = 'store_true',
                help = 'Report ARC command timing performance data per host '
                       'using labels of the form ARCCMD[HOST]. By default '
                       'report the aggretate time across hosts.')
        self._clean_url = None
        self._t_start = time.time()
        self._time_slots = 0
        self._grace_time = None

    def parse_args(self, args: List[str]) -> None:
        NagiosPlugin.parse_args(self, args)
        if not self.opts.url and not self.opts.dir_url:
            raise UsageError('You must provide either a --dir-url or a --url.')
        self.arcclient = ArcClient(self.perflog)

    def time_left(self) -> float:
        return self.opts.timeout - time.time() + self._t_start

    def next_timeout(self, which: str) -> float:
        assert self._time_slots > 0
        timeout = self.time_left() / self._time_slots - self._grace_time
        self._time_slots -= 1
        if timeout < 1:
            if self._clean_url and self._time_slots > 0:
                timeout = self.time_left()
                self.arcclient.arcrm(self._clean_url, timeout = timeout).get()
            raise ServiceCritical('Insufficient time for %s.'%which)
        return int(timeout)

    def check(self) -> ServiceReport:
        # Allocate up to 4 time slots for the main subtasks, and reserve a
        # fraction of the total time for the script itself and fork/exec
        # overhead.
        self._time_slots = \
                (self.opts.enable_read and 2 or 0) + \
                (self.opts.enable_write and 1 or 0) + \
                (self.opts.enable_list and 1 or 0)
        self._grace_time = self.opts.timeout * 0.02

        host = self.opts.host or 'localhost'
        timestamp = datetime.datetime.now().strftime('%Y%m%dT%H%M%S')

        self.require_voms_proxy()

        if self.opts.url:
            url = self.opts.url
            filename = os.path.basename(url)
        else:
            filename = '%s_%s.data'%(host, timestamp)
            url = os.path.join(self.opts.dir_url, filename)

        self.log.info('Performing checks on %s', url)
        failed_ops = []
        if self.opts.enable_write:
            timeout = self.next_timeout('write')
            uploaded_contents = 'Created by check_gridstorage %s for %s.\n' \
                    % (timestamp, self.opts.host or 'localhost')
            write_url = self.opts.write_url or url
            try:
                fd, outbound = self.mkstemp(prefix = 'outbound')
                fh = os.fdopen(fd, 'w')
                fh.write(uploaded_contents)
                fh.close()
            except OSError as exn:
                self.log.error('%s', exn)
                self.nagios_exit(UNKNOWN, 'Could not create test file.')
            arccp_result = \
                self.arcclient.arccp(outbound, write_url, timeout = timeout)
            if arccp_result.is_ok():
                self._clean_url = write_url
                self.log.info('Uploaded file.')
            else:
                log_process_error(self.log, arccp_result.error,
                                  synopsis = 'upload failed', prefix = 'arccp')
                failed_ops.append('upload')
        else:
            uploaded_contents = None

        if self.opts.enable_list:
            timeout = self.next_timeout('list')
            if self.opts.list_dir:
                list_url = self.opts.dir_url or os.path.dirname(url)
            else:
                list_url = url
            arcls_result = self.arcclient.arcls(list_url, timeout = timeout)
            if arcls_result.is_ok():
                listing = arcls_result.value
                self.log.info('Listing contains %d entries.', len(listing))
                if not any(os.path.basename(ent.filename) == filename
                           for ent in listing):
                    self.log.error('Did not find %s in listing.', filename)
                    failed_ops.append('list')
            else:
                log_process_error(self.log, arcls_result.get_error(),
                                  synopsis = 'listing failed', prefix = 'arcls')
                failed_ops.append('list')

        fetched_contents = None
        if self.opts.enable_read:
            timeout = self.next_timeout('read')
            inbound = self.mktemp(prefix = 'inbound')
            arccp_result = self.arcclient.arccp(url, inbound, timeout = timeout)
            if arccp_result.is_ok():
                self.remove_at_exit(inbound)
                try:
                    with open(inbound, encoding='utf-8') as fh:
                        fetched_contents = fh.read()
                    self.log.info('Fetched file.')
                except OSError as exn:
                    self.log.error('Could not open fetched file %s.', exn)
                    failed_ops.append('open-read')
            else:
                log_process_error(self.log, arccp_result.error,
                                  synopsis = 'fetch failed', prefix = 'arccp')
                failed_ops.append('fetch')

        if uploaded_contents and fetched_contents:
            if fetched_contents != uploaded_contents:
                self.log.error('Mismatched content in fetched file.')
                failed_ops.append('verify')
            else:
                self.log.info('Verified content of fetched file.')

        if self.opts.enable_write:
            timeout = self.next_timeout('remove')
            arcrm_result = self.arcclient.arcrm(url, timeout = timeout)
            if arcrm_result.is_ok():
                self.log.info('Removed file.')
            else:
                log_process_error(self.log, arcrm_result.error,
                                  synopsis = 'removal failed', prefix = 'arcrm')
                failed_ops.append('remove')
        if failed_ops:
            self.nagios_exit(CRITICAL, 'Failed to %s.'%', '.join(failed_ops))
        else:
            self.nagios_exit(OK, 'Storage tests succeeded.')
