#!/bin/bash

# Script to renew certificates with certbot
# Stops and starts nginx-proxy container to free ports 80 and 443

# Log the start of the script
echo "Certificate renewal started at $(date)"

# Stop Nginx Proxy to free ports 80 and 443
echo "Stopping nginx-proxy container..."
docker stop nginx-proxy-1
if [ $? -ne 0 ]; then
    echo "Failed to stop nginx-proxy container. Exiting."
    exit 1
fi

# Wait a moment for ports to be completely released
sleep 5

# Renew certificates
echo "Renewing certificates..."
certbot renew --standalone
CERTBOT_EXIT_CODE=$?

# Start Nginx Proxy again
echo "Starting nginx-proxy container..."
docker start nginx-proxy-1
if [ $? -ne 0 ]; then
    echo "Failed to start nginx-proxy container! Please check manually."
    exit 2
fi

# Check if certificate renewal was successful
if [ $CERTBOT_EXIT_CODE -ne 0 ]; then
    echo "Certificate renewal failed with exit code $CERTBOT_EXIT_CODE"
    exit 3
else
    echo "Certificate renewal completed successfully at $(date)"
fi

exit 0
