#!/bin/bash
source "${AGENT_PATH}/_common.sh"
_check_required_env_vars "CONTAINER_NAME" "VOLUME_NAME" "CONFIG_PATH" "IMAGE_REGISTRY" "IMAGE_REPO" "IMAGE_TAG"

# Simple Object Storage Start Script
# Creates and starts the container using environment variables.


# check volume exists.
if ! docker volume inspect "${VOLUME_NAME}" &>/dev/null; then
    _die "Docker volume ${VOLUME_NAME} does not exist"
fi

# determine port.
command -v jq &> /dev/null || _die "jq could not be found, please install it"
[ -f "${CONFIG_PATH}/sos_config.json" ] || _die "sos_config.json does not exist"
PORT=$(jq -r '.port' "${CONFIG_PATH}/sos_config.json")


DOCKER_RUN_CMD="docker run -d \
                --restart unless-stopped \
                --name ${CONTAINER_NAME} \
                -p ${PORT}:${PORT} \
                -v ${VOLUME_NAME}:/data/storage \
                -v ${CONFIG_PATH}/sos_config.json:/data/sos_config.json:ro \
                ${IMAGE_REGISTRY}/${IMAGE_REPO}:${IMAGE_TAG}"


if ! create_and_start_container "$DOCKER_RUN_CMD" "$CONTAINER_NAME"; then
    _die "Failed to start container ${CONTAINER_NAME}"
fi

# Check if the container is running
if ! _is_container_running "$CONTAINER_NAME"; then
    _die "Container ${CONTAINER_NAME} is not running"
fi

echo "Container ${CONTAINER_NAME} started"
