################################################################################
# For restarts @4am
# https://stackoverflow.com/questions/69309747/schedule-daily-docker-container-restart-reset
###############################################################################

version: "3.9"
services:
  restart-er:
    container_name: restart-er
    image: docker:cli
    restart: unless-stopped
    volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
    entrypoint: ["/bin/sh","-c"]
    command:
      - |
        RESTARTED_TODAY=false # Flag to track if containers have been restarted today
        while true; do
            CURRENT_TIME=$(date +'%H:%M')
            if [ "$CURRENT_TIME" = '04:00' ]; then
                if [ "$RESTARTED_TODAY" = false ]; then
                    echo "$(date): It's 04:00. Initiating Docker container restart process..."

                    CONTAINER_IDS=$(docker ps -q)

                    if [ -z "$CONTAINER_IDS" ]; then
                        echo "$(date): No running Docker containers found to restart."
                    else
                        echo "$(date): Found containers: $CONTAINER_IDS"
                        for CONTAINER_ID in $CONTAINER_IDS; do
                            echo "$(date): Restarting container: ${CONTAINER_ID}"
                            docker restart "${CONTAINER_ID}"
                            # Check if the restart command was successful (optional, but good practice)
                            if [ $? -eq 0 ]; then
                                echo "$(date): Successfully restarted ${CONTAINER_ID}."
                            else
                                echo "$(date): Failed to restart ${CONTAINER_ID}. Continuing to next container."
                            fi
                            echo "$(date): Waiting 10 seconds before next container restart..."
                            sleep 10
                        done
                        echo "$(date): All specified Docker containers have been processed for restart."
                    fi
                    RESTARTED_TODAY=true # Set the flag to true to prevent re-running until next day
                    echo "$(date): Restart cycle for today (04:00) completed."
                else
                    echo "$(date): It's 04:00, but containers already restarted today. Skipping."
                fi
            else
                # Reset the flag once the time passes 04:00, preparing for the next day's restart
                if [ "$RESTARTED_TODAY" = true ]; then
                    echo "$(date): Time is no longer 04:00. Resetting restart flag for tomorrow."
                    RESTARTED_TODAY=false
                fi
            fi

            # Sleep for a shorter duration (e.g., 30 seconds) to ensure the 04:00 mark is caught reliably,
            # but not so short as to consume excessive CPU.
            sleep 30
        done