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

if ! autocreate volume=$DATA_VOLUME volume=$CONFIG_VOLUME; then
    _die "Failed to autocreate volumes and paths"
fi

_check_docker_installed || _die "Docker test failed, aborting installation..."

docker pull "$IMAGE_REGISTRY/$IMAGE_REPO:$IMAGE_TAG" || _die "Failed to pull image $IMAGE_REGISTRY/$IMAGE_REPO:$IMAGE_TAG"

[ -f "${CONFIG_PATH}/Caddyfile" ] || _die "Caddyfile not found in ${CONFIG_PATH}!"

bash ./stop.sh || _die "Failed to stop container ${CONTAINER_NAME}"
_remove_container $CONTAINER_NAME || _die "Failed to remove container ${CONTAINER_NAME}"
bash ./start.sh || _die "Failed to start container ${CONTAINER_NAME}"

echo "Installation of ${CONTAINER_NAME} complete"
