#! /bin/bash

#
# cert-renew.sh, script per rinnovare il certificato del server LDAP
#
# Copyright (C) 2025 FUSS Project <info@fuss.bz.it>
# Authors: Simone Piccardi <piccardi@truelite.it>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA
#

usage () {
    echo "Usage: ./cert-renew.sh [days]"
    echo "  renew an expired SSL certificate for the LDAP server"
    echo "  new certificate will last 5 year"
    echo "  optionally take as argument a number of days before expiration"
    echo "  and force renewal"
}

# check syntax
if [ "$#" -gt 1 ]; then
    echo Too many arguments: you can pass at most a number of days
    usage
    exit 1
fi

# take number of days before expiration
if [ "$#" = 1 ]; then
    BEFORE=$(( $1 * 86400 ))
else
    BEFORE=0
fi
    
# Get easyrsa PKI data DIR
PKI_DIR=$(find /etc/fuss-server/ -name pki)
KEY_FILE=$(grep TLSCertificateKeyFile /etc/ldap/slapd.conf|awk '{print $2}')
CERT_FILE=$(grep TLSCertificateFile /etc/ldap/slapd.conf|awk '{print $2}')
CN=$(openssl x509 -subject -noout -in $CERT_FILE|cut -d= -f3)
CERT_CN=$(echo $CN)

EXPIRE=$(openssl x509 -enddate -noout -in $CERT_FILE|cut -d= -f2|date +%s -f -)
ENDATE=$(openssl x509 -enddate -noout -in $CERT_FILE|cut -d= -f2)
DAYS=$(( 365 * 5 ))
LIMIT=$(( $(date +%s) + $BEFORE ))

if [ $EXPIRE -lt $LIMIT ]; then
    if [ "$BEFORE" != 0 ]; then
	echo Certificate expired on $ENDATE renewing
    else
	echo Expiring $(date +%F\ %R -d "$ENDATE"), before $(date +%F\ %R -d @$LIMIT) limit
	echo renewing certificate
    fi
    # Go un the base directory for issuing command
    cd $PKI_DIR/..
    [ -d oldCERTS ] || mkdir oldCERTS
    mv -f --backup=numbered pki/issued/$CERT_CN.crt oldCERTS
    mv -f --backup=numbered pki/private/$CERT_CN.key oldCERTS
    mv -f --backup=numbered pki/reqs/$CERT_CN.req oldCERTS
    mv -f --backup=numbered $CERT_FILE oldCERTS
    mv -f --backup=numbered $KEY_FILE  oldCERTS
    ./easyrsa --batch --days=$DAYS build-serverClient-full $CERT_CN nopass
    cp -a pki/issued/$CERT_CN.crt $CERT_FILE
    cp -a pki/private/$CERT_CN.key $KEY_FILE
    chmod g+r $KEY_FILE
    chgrp ssl-cert $KEY_FILE
    chmod +r $CERT_FILE
    systemctl restart slapd.service
else
    echo Certificate still valid, expiring $ENDATE
fi

