#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only

from cryptography import x509

import univention_baseconfig

_bc = univention_baseconfig.baseConfig()
_bc.load()


def get_validity_date(certFile):
    """returns the validity date fo the locale SSL certificate or None on failure"""
    try:
        with open(certFile, 'rb') as fd:
            cert = x509.load_pem_x509_certificate(fd.read())
        return cert.not_valid_after
    except Exception:
        return None


def get_validity_days(certFile):
    """
    returns the validity of the local SSL certificate in days. If the
    validity could not be determined 0 is returned
    """
    after = get_validity_date(certFile)
    if after:
        return int(after.timestamp()) // 60 // 60 // 24

    return 0


if __name__ == '__main__':
    fqdn = '.'.join([_bc['hostname'], _bc['domainname']])
    certFile = '/etc/univention/ssl/%s/cert.pem' % fqdn
    days = get_validity_days(certFile)
    if days and days != _bc.get('ssl/validity/days', -1):
        _bc['ssl/validity/days'] = str(days)
        _bc.save()
