#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
## Datum: 18.04.2024 (Update)
## Version: 1.1 (Rolling 24h)
## Voraussetzungen: python 2.7, python-tz
## Beschreibung: Lokaler Check_MK-Check fr Cryptshare (rollende 24h-Statistik)

from pytz import timezone
from datetime import datetime
import time
import os

# --- KONFIGURATION ---
# Pfad zum Cryptshare-Upload-Verzeichnis
dir1 = "/var/opt/cryptshare/uploads/"
# Zeitzone
tz_europe = timezone('Europe/Berlin')

# --- ZEITBERECHNUNG ---
# Aktuelle Zeit in Epoch (Sekunden seit 1.1.1970)
now_epoch = time.time()
# Zeitstempel vor genau 24 Stunden
last_24h_epoch = now_epoch - (24 * 60 * 60)

# --- VARIABLEN ---
files_all_list = []
files_all_time = []
files_all_groesse = []

files_24h_time = []
files_24h_groesse = []

def find_files(path):
    """Sammelt alle Dateipfade im angegebenen Verzeichnis."""
    found_files = []
    try:
        if os.path.exists(path):
            dirlist = os.listdir(path)
            for element in dirlist:
                full_path = os.path.join(path, element)
                if os.path.isfile(full_path):
                    found_files.append(full_path)
    except Exception, e:
        print "Error accessing directory:", e
    return found_files

# --- DATENERHEBUNG ---
files_all_list = find_files(dir1)

for element in files_all_list:
    try:
        # Erstellungszeit (ctime) und Groesse (size) ermitteln
        f_time = os.path.getctime(element)
        f_size = os.path.getsize(element)
        
        # Statistiken fuer "Gesamt"
        files_all_time.append(int(f_time))
        files_all_groesse.append(f_size)
        
        # Statistiken fuer "letzte 24 Stunden"
        if f_time > last_24h_epoch:
            files_24h_time.append(int(f_time))
            files_24h_groesse.append(f_size)
            
    except Exception, e:
        # Falls eine Datei waehrend des Scans geloescht wurde
        pass

# --- BERECHNUNG ---
# Gesamt
all_transfers = len(set(files_all_time)) # Eindeutige Zeitstempel = Transfers
all_files = len(files_all_time)
all_sum_size = sum(files_all_groesse)

# Letzte 24 Stunden
last24_transfers = len(set(files_24h_time))
last24_files = len(files_24h_time)
last24_sum_size = sum(files_24h_groesse)

# --- AUSGABE ---
# Check_MK Sektions-Header
print "<<<cryptshare_check>>>"

# Format:
# Bereitstellungen [24h-Transfers] [24h-Dateien] [24h-Bytes] [Gesamt-Transfers] [Gesamt-Dateien] [Gesamt-Bytes]
print "Bereitstellungen %d %d %d %d %d %d" % (
    last24_transfers, 
    last24_files, 
    last24_sum_size, 
    all_transfers, 
    all_files, 
    all_sum_size
)
