#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# NOTE: Careful when replacing the *-import below with a more specific import. This can cause
# problems because it might remove variables from the check-context which are necessary for
# resolving legacy discovery results such as [("SUMMARY", "diskstat_default_levels")]. Furthermore,
# it might also remove variables needed for accessing discovery rulesets.
from cmk.base.check_legacy_includes.df import *  # pylint: disable=wildcard-import,unused-wildcard-import
# NOTE: Careful when replacing the *-import below with a more specific import. This can cause
# problems because it might remove variables from the check-context which are necessary for
# resolving legacy discovery results such as [("SUMMARY", "diskstat_default_levels")]. Furthermore,
# it might also remove variables needed for accessing discovery rulesets.
from cmk.base.check_legacy_includes.size_trend import *  # pylint: disable=wildcard-import,unused-wildcard-import
# <<<df_zos>>>
# SYS5.OMVS.ALF0.HFS         720          92        504       16% /ALF0
# HFS, Read/Write, Device:2, ACLS=Y
# Filetag : T=off   codeset=0
# ##########
# SYS5.OMVS.SYSPLEX.ROOT     720         224        372       38% /
# HFS, Read Only, Device:1, ACLS=Y
# Filetag : T=off   codeset=0
# ##########

# FS Types:
# AUTOMNT
# TFS
# ZFS
# NFS
# HFS


def parse_df_zos(info):
    parsed = {}
    fs = None
    usage = []
    options = []

    for line in info:
        if line[0].startswith('#####'):
            # Add item for filesystem
            if fs and usage and options:
                parsed.setdefault(fs, {})
                parsed[fs].setdefault('size', usage)
                parsed[fs].setdefault('options', options)

            fs = None
            usage = []
            options = []
        elif line[0].startswith('Filesystem'):
            # Ignore header line
            continue
        else:
            if fs is None:
                # First line: filesystem with usage information
                fs = line[5]
                usage = line[1:5]
            elif not options:
                # Second line: filesystem options
                for option in line:
                    options.append(option.replace(',', ''))
                if 'Read' in options and 'Only' in options:
                    options.remove('Read')
                    options.remove('Only')
                    options.append('ReadOnly')
    return parsed


df_zos_exclude_list = ['AUTOMNT', 'TFS', 'NFS']


def inventory_df_zos(parsed):
    mplist = []

    for item in parsed:
        fs_rw = False
        fs_ex = False

        # Check filesystem options
        for option in parsed[item]['options']:
            # Check if filesystem is rw
            if option == 'Read/Write':
                fs_rw = True

            # Check if filesystem is excluded
            if option in df_zos_exclude_list:
                fs_ex = True

        if fs_rw and not fs_ex:
            mplist.append(item)
    return df_inventory(mplist)


def check_df_zos(item, params, parsed):
    fslist = []

    for filesystem, fs_data in parsed.items():
        (size_mb, used_mb, avail_mb) = map(float, fs_data['size'][0:3])
        size_mb /= 1024
        used_mb /= 1024
        avail_mb /= 1024
        fslist.append((filesystem, size_mb, avail_mb, 0))

    return df_check_filesystem_list(item, params, fslist)


check_info['df_zos'] = {
    'parse_function': parse_df_zos,
    'check_function': check_df_zos,
    'inventory_function': inventory_df_zos,
    'service_description': "Filesystem %s",
    'has_perfdata': True,
    'group': 'filesystem',
    'default_levels_variable': "filesystem_default_levels",
}
