#!/usr/bin/env python


import re
import commands


class Redis:
    def __init__(self, agent_config, checks_logger, raw_config):
        self.agent_config = agent_config
        self.checks_logger = checks_logger
        self.raw_config = raw_config

    def run(self):
        stats = {}
        status, out = commands.getstatusoutput(self.redis_info_cmd())
        if status != 0:
            return stats
        # Grab every statistic available and leave it to the end user to
        # determine which fields they care about
        for key, val in [line.split(':') for line in out.splitlines()]:
            m = re.search("keys=([0-9]*),expires=([0-9]*)", val)
            if m != None:
                stats[key+"_keys"] = m.group(1)
                stats[key+"_expires"] = m.group(2)
            stats[key] = val
        status, out = commands.getstatusoutput("redis-cli config get maxmemory | tail -1 | tr -d '\n'")
        if status != 0:
            return stats
        stats['maxmemory'] = out.splitlines()[0]
        if stats['maxmemory']:
            stats['remaining_memory'] = int(stats['maxmemory']) - int(stats['used_memory'])
            stats['percent_memory_used'] = (int(stats['used_memory']) / float(stats['maxmemory'])) * 100
        return stats

    def redis_info_cmd(self):
        if self.raw_config.get('Redis') and self.raw_config['Redis'].get('password'):
                self.checks_logger.debug('Found Redis password in config')
                return "redis-cli -a %s info" % self.raw_config['Redis']['password']
        else:
                return "redis-cli info"


if __name__ == '__main__':
    redis = Redis(None, None, None)
    print redis.run()
