#!/bin/sh

# Default configurations
CERT_DIR="/usr/local/etc/cert.d"
DAYS=30
EXTENSIONS="pem crt"
LOG_FILE="/var/log/cert_expiration.log"

usage() {
    echo "Usage: $0 [-d directory] [-t days] [-e \"ext1 ext2\"] [-l logfile]"
    echo "  -d  Directory containing certificates (default: /usr/local/etc/cert.d)"
    echo "  -t  Expiration threshold in days (default: 30)"
    echo "  -e  Space-separated list of file extensions (default: \"pem crt\")"
    echo "  -l  Log file path for full output (default: /var/log/cert_expiration.log)"
    exit 2
}

while getopts "d:t:e:l:h" opt; do
    case "$opt" in
        d) CERT_DIR="$OPTARG" ;;
        t) DAYS="$OPTARG" ;;
        e) EXTENSIONS="$OPTARG" ;;
        l) LOG_FILE="$OPTARG" ;;
        h|\?) usage ;;
    esac
done

if [ ! -d "$CERT_DIR" ]; then
    echo "CRITICAL: Directory '$CERT_DIR' does not exist."
    exit 2
fi

NOW=$(date +%s)
SECONDS_THRESHOLD=$(( DAYS * 86400 ))

# Temp storage for collecting results
OUT_TMP=$(mktemp /tmp/cert_out.XXXXXX)

for ext in $EXTENSIONS; do
    for cert in "$CERT_DIR"/*."$ext"; do
        if [ ! -f "$cert" ]; then
            continue
        fi

        TMP_BLOCK=$(mktemp /tmp/cert_block.XXXXXX)

        awk '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/ { print }' "$cert" | \
        while read -r line; do
            echo "$line" >> "$TMP_BLOCK"
            
            if [ "$line" = "-----END CERTIFICATE-----" ]; then
                EXP_DATE_STR=$(openssl x509 -enddate -noout -in "$TMP_BLOCK" 2>/dev/null | cut -d= -f2)
                SUBJECT_CN=$(openssl x509 -subject -noout -in "$TMP_BLOCK" 2>/dev/null | sed -n 's/.*CN = //p')
                
                if [ -n "$EXP_DATE_STR" ]; then
                    EXP_EPOCH=$(date -j -f "%b %d %T %Y %Z" "$EXP_DATE_STR" "+%s" 2>/dev/null)
                    
                    if [ -z "$EXP_EPOCH" ]; then
                        EXP_EPOCH=$(date -j -f "%b %e %T %Y" "$(echo "$EXP_DATE_STR" | sed 's/ GMT//')" "+%s" 2>/dev/null)
                    fi

                    if [ -n "$EXP_EPOCH" ]; then
                        DIFF_SECONDS=$(( EXP_EPOCH - NOW ))

                        if [ "$DIFF_SECONDS" -lt 0 ]; then
                            OVERDUE_DAYS=$(( (NOW - EXP_EPOCH) / 86400 ))
                            echo "EXPIRED (${OVERDUE_DAYS}d ago): ${cert##*/} [CN: ${SUBJECT_CN:-unknown}]" >> "$OUT_TMP"
                        elif [ "$DIFF_SECONDS" -le "$SECONDS_THRESHOLD" ]; then
                            REMAINING_DAYS=$(( DIFF_SECONDS / 86400 ))
                            echo "EXPIRING (${REMAINING_DAYS}d left): ${cert##*/} [CN: ${SUBJECT_CN:-unknown}]" >> "$OUT_TMP"
                        fi
                    fi
                fi
                : > "$TMP_BLOCK"
            fi
        done

        rm -f "$TMP_BLOCK"
    done
done

TOTAL_ISSUES=$(wc -l < "$OUT_TMP" | tr -d ' ')

if [ "$TOTAL_ISSUES" -gt 0 ]; then
    # Write full detailed audit to log file on disk
    echo "=== Certificate Audit $(date) ===" >> "$LOG_FILE"
    cat "$OUT_TMP" >> "$LOG_FILE"
    echo "" >> "$LOG_FILE"

    # Format stdout for Monit email (Header + first few lines only to prevent truncation)
    echo "Found $TOTAL_ISSUES problem certs (Full log at $LOG_FILE):"
    head -n 5 "$OUT_TMP"
    if [ "$TOTAL_ISSUES" -gt 5 ]; then
        EXCESS=$(( TOTAL_ISSUES - 5 ))
        echo "... and $EXCESS more certificates."
    fi

    rm -f "$OUT_TMP"
    exit 1
fi

rm -f "$OUT_TMP"
exit 0