#!/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.

import os
from typing import Any, Dict

# sample configuration:
# mode = "nc"    # "nc" = use netcat, "tool" = use memcached-tool
# instances = [
#  ("localhost", 11211),
#  ("localhost", 11212)
# ]

settings = {}  # type: Dict[str, Any]
config_file = os.path.join(os.environ.get("MK_CONFDIR", "/etc/check_mk"), "memcached.cfg")
if os.path.exists(config_file):
    exec(open(config_file).read(), settings, settings)

if 'instances' in settings:
    print("<<<memcached>>>")
    if settings.get("mode", "nc"):
        cmdline = 'echo "stats" | nc %s %s |sed -e "s/\\(STAT \\|END\\)//"'
    else:
        cmdline = 'memcached-tool %s:%s stats'

    for instance in settings['instances']:
        print("[%s:%s]" % (instance[0], instance[1]))
        for line in os.popen(cmdline % instance):  # nosec
            print(line.strip())
