#!/usr/bin/env python3

# ----------------------------------------------------------------------
# File: eos-inspectorstat
# Author: Andreas-Joachim Peters - CERN
# ----------------------------------------------------------------------

# ************************************************************************
# * EOS - the CERN Disk Storage System                                   *
# * Copyright (C) 2024 CERN/Switzerland                                  *
# *                                                                      *
# * This program is free software: you can redistribute it and/or modify *
# * it under the terms of the GNU General Public License as published by *
# * the Free Software Foundation, either version 3 of the License, or    *
# * (at your option) any later version.                                  *
# *                                                                      *
# * This program is distributed in the hope that it will be useful,      *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
# * GNU General Public License for more details.                         *
# *                                                                      *
# * You should have received a copy of the GNU General Public License    *
# * along with this program.  If not, see <http://www.gnu.org/licenses/>.*
# ************************************************************************

import sys
import time
import json
import os

costinspector = {}

now = int(time.time())

def dict2prom(data_dict):
    prefix = "eos"
    category = "inspector"
    subcategory = "user"
    metric_name = "_".join([prefix, category, subcategory])
    help_text = "User storage costs derived from inspector output"

    prom_output = f"# HELP {metric_name} {help_text}\n"
    prom_output += f"# TYPE {metric_name} gauge\n"

    for uid, metrics in data_dict.items():
        if uid == "uid":
            continue

        for metric, value in metrics.items():
            if metric == "uid":
                continue

            prom_output += f"{metric_name}{{uid=\"{uid}\", measure=\"{metric}\"}}" f" {value}\n"

    return prom_output

IGNORED_KEYS = {"tag", "username", "key"}

def read_textfile(file_path, cost):
    with open(file_path, 'r') as file:
        for line in file:
            data = dict(item.split('=', 1) for item in line.strip().split())
            uid = data.get('uid')
            if uid:
                cost.setdefault(uid, {})
                for key, value in data.items():
                    if key not in IGNORED_KEYS:
                        cost[uid][key] = value
                cost[uid]["unixtime"] = int(time.time())
    return cost

arguments = sys.argv

f = "/var/eos/md/inspectorstats.0"

tofile=""
tofiletmp=""
promfile=""
promfiletmp=""

if len(arguments) > 1:
    f = arguments[1]
else:
    tofile="/var/eos/md/inspector-report.json"
    tofiletmp = tofile + ".tmp"
    promfile="/var/eos/md/inspector-report.prom"
    promfiletmp = promfile + ".tmp"
    
read_textfile(f, costinspector)

jsondump = json.dumps(costinspector, indent=4)
if len(tofile):
    with open(tofiletmp, "w") as file:
        file.write(jsondump)
        os.rename(tofiletmp,tofile)

if len(promfile):
    with open(promfiletmp, "w") as file:
        file.write(dict2prom(costinspector))
        os.rename(promfiletmp, promfile)
else:
    print(jsondump)
