#!/usr/bin/python3

import json
import os.path
from datetime import datetime

configuration = { 'max_age': 129600 }

def print_result(status=100, message='', detail={}):
    if status == 100:
        value = 'OK'
    elif 100 < status <= 199:
        value = 'INFO'
    elif 200 <= status <= 299:
        value = 'WARN'
    elif 300 <= status <= 499:
        value = 'CRIT'
    else:
        value = 'ERROR'

    result = {
        'Detail': detail,
        'Message': message,
        'Value': value,
        'Status': status,
        'Version': '0.10',
        'Metrics': []
    }

    print(json.dumps(result))


def check_backup():
    if not os.path.isfile('/var/tmp/restic.json'):
        status = 500
        message = "No backup status found."
        detail = {}
    else:
        try:
            with open('/var/tmp/restic.json', 'r') as status_file:
                js = json.load(status_file)
        except json.decoder.JSONDecodeError:
            status = 300
            message = "Json file is malformed."
            detail = {}
        else:
            last_backup = datetime.fromisoformat(js[0]['time'][0:19])
            current_date = datetime.now()
            detail = js

            diff = current_date - last_backup

            if int(diff.total_seconds()) > configuration['max_age']:
                status = 250
                message = "The backup is to old, it happens {} seconds ago.".format(diff.seconds)
            else:
                status = 100
                message = "Everything is fine, last backup at {}".format(last_backup)

    print_result(status, message, detail)


if __name__ == "__main__":
    check_backup()
