#!/usr/bin/python3

import os
import sys
import glob
import time
import re

def kmgt(sz, frac=1):
    t = {
        'K': pow(1024, 1),
        'M': pow(1024, 2),
        'G': pow(1024, 3),
        'T': pow(1024, 4),
        '': 1}

    for k in sorted(t, key=t.__getitem__, reverse=True):
        if sz >= t[k]:
            n = sz / float(t[k])
            tpl = "{:." + str(frac) + "f}{}"
            return tpl.format(n, k)

def timesuffix2sec(timesuffix):
    suf = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}

    r = re.match('(\d+)(d|h|m|s|day|days|hour|hours|hr|min|minute|minutes|sec|seconds)?$', timesuffix)
    if r is None:
        raise ValueError('Cannot parse \'{}\'. Valid examples are: 10s, 5m, 2h'.format(timesuffix))

    r = re.match('(\d+)([dhmsDHMS])?', timesuffix)
    if r is None:
        raise ValueError('Bad time/suffix value {}'.format(timesuffix))

    n = int(r.group(1))
    try:
        suffix = r.group(2).lower()
    except:
        suffix = 's'
    return n * suf[suffix]


if len(sys.argv) == 1:
    method = 'info'
else:
    method = sys.argv[1]

if method == 'info':
    info = {
        'Protocol': '0.1',
        'Description': 'Check freshness for backup files',
        'Version': '0.1',
        'Methods': 'check makeconfig info'
    }
    for k, v in info.items():
        print("{}: {}".format(k, v))

elif method == 'check':
    # read parameters
    prefix = os.getenv('PREFIX')
    pathlist = os.getenv('PATHLIST','/var/mybackups/*')
    fresh = timesuffix2sec(os.getenv('FRESH','1d'))
    date = os.getenv('DATEFMT','[0-9][0-9\-]{7,}')
    datesub = os.getenv('DATESUB','DATE')
    minlim = os.getenv('MINLIM','10k')
    diffmin = os.getenv('DIFFMIN','0')
    skip = os.getenv('SKIP','')

    for path in pathlist.split(' '):
        for curpath in glob.glob(path):

            if skip and re.search(skip, curpath):
                continue

            if time.time() - os.stat(curpath).st_mtime > fresh:
                continue

            tpl = re.sub(date, datesub, os.path.basename(curpath))
            sz = os.stat(curpath).st_size
            print("TPL: {}".format(tpl))

            print("NAME: {}{}".format(prefix, tpl))
            print("TAGS: backups")
            print("DETAILS: {}: {}".format(os.path.basename(curpath), kmgt(sz)))
            print("METHOD: numerical|minlim={}|diffmin={}".format(minlim, diffmin))
            print("STATUS: {}".format(sz))
            print()

elif method=='makeconfig':

    data="""
#
# Env configurational file for 'maxfilesz' check
#

# Space-separated files to check (glob)
# PATHLIST=/var/log 
PATHLIST=/var/mybackups/*gz

# Which backups (age) we report to server. Use seconds or use suffix d,h,m or s
FRESH=1d

# DATE format in your backup files (regex)
# default matches backups like name-2019-12-31.tar.gz
# indicator name will be name-DATE.tar.gz
DATEFMT=\d[\d\-]{6,}\d

# date regex will be replaced to DATESUB value
DATESUB=DATE

# alert if backup is smaller then this size (e.g. if empty file or empty tar.gz file)
MINLIM=10k

# use to set diffmin. if DIFFMIN=0, alert will be send if new backup is smaller then older
DIFFMIN=0

# use this for secondary prefix: hostname:backups:name-DATE.tar.gz instead or hostname:name-DATE.tar.gz
#PREFIX2=backups:

# regex to skip these files (empty: do not skip anything)
SKIP=

""".strip()

    print(data)