#!/usr/bin/python3
# Author: Yannik Enss
import subprocess
import datetime
import argparse
import enum
import os
import sys
from email.utils import parsedate_to_datetime

class Status(enum.Enum):
    OK = 0
    WARNING = 1
    CRITICAL = 2
    UNKNOWN = 3

def get_expiry_date(filename):
    finished_process = subprocess.run(
        ["openssl",
         "x509",
         "-in", filename,
         "-enddate",
         "-noout"],
        text=True, capture_output=True, check=True)
    date = finished_process.stdout.strip().split("=")[1]
    date = parsedate_to_datetime(date)
    return date

def is_expired(filename, days_from_now=0):
    finished_process = subprocess.run(
        ["openssl",
         "x509",
         "-in", filename,
         "-checkend", str(days_from_now*24*60*60),
         "-noout"],
        stdout=subprocess.DEVNULL)
    
    if finished_process.returncode == 0:
        return False
    else:
        return True
 
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("file")
    parser.add_argument("--warning-threshold", "-w", type=int, default=30)
    parser.add_argument("--critical-threshold", "-c", type=int, default=7)
    args = parser.parse_args()

    status = Status.UNKNOWN
    message = "Plugin failed"
    perfdata = {}

    if not os.path.isfile(args.file):
        status = Status.UNKNOWN
        message = "File not found"

    else:
        try:
            expiry_date = get_expiry_date(args.file)


            perfdata["expires_in"] = (expiry_date - datetime.datetime.now(expiry_date.tzinfo)).days

            if is_expired(args.file, 0):
                message = f"Expired on {expiry_date}"
                status = Status.CRITICAL

            elif is_expired(args.file, args.critical_threshold):
                message = f"Will expire on {expiry_date}"
                status = Status.CRITICAL

            elif is_expired(args.file, args.warning_threshold):
                message = f"Will expire on {expiry_date}"
                status = Status.WARNING

            else:
                message = f"Will expire on {expiry_date}"
                status = Status.OK

        except Exception as e:
            message = f"Failed: {e}"
            status = Status.UNKNOWN

    perfdata_str = ""
    for key,value in perfdata.items():
        perfdata_str += f"|{key}={value}"

    print(f"{status.name}: {message}{perfdata_str}")
    sys.exit(status.value)


