#!/bin/bash
# EXIM ERP SSL Certificate Renewal Script
# Runs via cron to renew Let's Encrypt certificates

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Configuration
LOG_FILE="/var/log/ssl-renewal.log"
DOMAIN="exim-erp.example.com"

log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

print_status "Starting SSL certificate renewal check..."

# Check if certbot is installed
if ! command -v certbot &> /dev/null; then
    print_error "Certbot is not installed. Please install it first."
    log_message "ERROR: Certbot not installed"
    exit 1
fi

# Check current certificate expiry
CERT_FILE="/etc/letsencrypt/live/$DOMAIN/fullchain.pem"
if [ -f "$CERT_FILE" ]; then
    EXPIRY=$(openssl x509 -enddate -noout -in "$CERT_FILE" 2>/dev/null | cut -d= -f2)
    EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s 2>/dev/null || echo 0)
    CURRENT_EPOCH=$(date +%s)
    DAYS_LEFT=$(( ($EXPIRY_EPOCH - $CURRENT_EPOCH) / 86400 ))
    
    print_status "Current certificate expires in $DAYS_LEFT days"
    
    # Renew if less than 30 days remaining
    if [ "$DAYS_LEFT" -lt 30 ]; then
        print_status "Certificate needs renewal. Attempting renewal..."
        
        # Attempt renewal
        certbot renew --quiet --no-self-upgrade --deploy-hook "systemctl reload nginx"
        
        if [ $? -eq 0 ]; then
            print_status "SSL certificate renewed successfully!"
            log_message "SSL certificate renewed successfully"
            
            # Reload Nginx
            systemctl reload nginx
            print_status "Nginx reloaded"
        else
            print_error "SSL certificate renewal failed!"
            log_message "ERROR: SSL certificate renewal failed"
            exit 1
        fi
    else
        print_status "Certificate is still valid. No renewal needed."
    fi
else
    print_warning "Certificate file not found. Attempting initial setup..."
    log_message "Certificate file not found, attempting setup"
    
    # Try to obtain certificate
    certbot certonly --nginx -d "$DOMAIN" --non-interactive --agree-tos --email "admin@$DOMAIN"
    
    if [ $? -eq 0 ]; then
        print_status "SSL certificate obtained successfully!"
        log_message "SSL certificate obtained successfully"
        systemctl reload nginx
    else
        print_error "Failed to obtain SSL certificate!"
        log_message "ERROR: Failed to obtain SSL certificate"
        exit 1
    fi
fi

print_status "SSL renewal check completed at $(date)"
