#!/usr/bin/env bash

# DLM Certbot Automatic Certificate Renewal Script
# This script is designed to be run daily via cron

# Install to Crontab:
# ln -sf /opt/moxa/dlm/bin/dlm-certbot-cron /etc/cron.daily/dlm-certbot

# Set up logging
LOG_FILE="/var/log/dlm/certbot-cron.log"
mkdir -p "$(dirname "$LOG_FILE")"

# Function to log with timestamp
log_with_timestamp() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

log_with_timestamp "=== DLM Certbot Cron Job Started ==="

# Set the PATH to ensure all required commands are available
export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

# Change to the script directory
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
cd "$SCRIPT_DIR" || {
    log_with_timestamp "Error: Failed to change to script directory: $SCRIPT_DIR"
    exit 1
}

# Source environment variables
if [ -f "../static-config/env-files/manifest.env" ]; then
    # shellcheck disable=SC2046
    export $(grep -v '^#' "../static-config/env-files/manifest.env" | xargs)
fi

USER_DATA_DIR="/var/lib/dlm"
if [ -f "$USER_DATA_DIR/env-files/global.env" ]; then
    # shellcheck disable=SC2046
    export $(grep -v '^#' "$USER_DATA_DIR/env-files/global.env" | xargs)
fi

log_with_timestamp "Environment variables loaded"

# Run the dlm certbot command
log_with_timestamp "Executing dlm certbot command"

# Set caller to 'cron' to prevent interactive prompts
export caller="cron"

# Execute the certbot renewal
if ./dlm certbot >> "$LOG_FILE" 2>&1; then
    log_with_timestamp "DLM Certbot completed successfully"
    exit_code=0
else
    log_with_timestamp "DLM Certbot failed with exit code $?"
    exit_code=1
fi

log_with_timestamp "=== DLM Certbot Cron Job Finished (exit code: $exit_code) ==="

# Keep log file size manageable (keep last 1000 lines)
if [ -f "$LOG_FILE" ]; then
    tail -n 1000 "$LOG_FILE" > "$LOG_FILE.tmp" && mv "$LOG_FILE.tmp" "$LOG_FILE"
fi

exit $exit_code