#!/bin/bash
source "${AGENT_PATH}/_common.sh"
_check_required_env_vars

# Watchtower Start Script


# Load service environment variables
source ./service.env

# Optional arguments (e.g., --cleanup, --monitor-only)
EXTRA_ARGS=$1

DOCKER_RUN_CMD="docker run -d \
    --name ${CONTAINER_NAME} \
    --restart=always \
    -v /var/run/docker.sock:/var/run/docker.sock \
    ${IMAGE_REGISTRY}/${IMAGE_REPO}:${IMAGE_TAG} \
    --interval ${INTERVAL} ${EXTRA_ARGS}"

echo "Starting container ${CONTAINER_NAME}..."

if ! _create_and_start_container "$DOCKER_RUN_CMD" "$CONTAINER_NAME"; then
    # If creation/start failed, attempt to display logs if container exists
    if _is_container_exists $CONTAINER_NAME; then
        echo "Attempting to get logs from failed container..."
        _get_container_logs $CONTAINER_NAME
    fi
    _die "Failed to start container ${CONTAINER_NAME}"
fi

# Check if the container is running after successful start command
if ! _is_container_running "$CONTAINER_NAME"; then
     _get_container_logs $CONTAINER_NAME # Show logs if it immediately exited
    _die "Container ${CONTAINER_NAME} is not running after start attempt"
fi

echo "Service ${CONTAINER_NAME} started successfully."
