#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

DOCKER_CMD=()
SECRETS_FILE="$SCRIPT_DIR/.mongo-secrets.env"
COMPOSE_ENV_FILE="$(mktemp)"

if [ -f "$SECRETS_FILE" ]; then
	# shellcheck disable=SC1090
	source "$SECRETS_FILE"
fi

cat > "$COMPOSE_ENV_FILE" <<EOF
MONGO_INITDB_ROOT_USERNAME=${MONGO_INITDB_ROOT_USERNAME:-website_root}
MONGO_INITDB_ROOT_PASSWORD=${MONGO_INITDB_ROOT_PASSWORD:-placeholder-stop-password}
MONGO_APP_USER=${MONGO_APP_USER:-website_app}
MONGO_APP_PASSWORD=${MONGO_APP_PASSWORD:-placeholder-stop-password}
MONGO_DB_NAME=${MONGO_DB_NAME:-Invario_Website}
EOF

cleanup() {
	rm -f "$COMPOSE_ENV_FILE"
}
trap cleanup EXIT

resolve_docker_cmd() {
	if docker info >/dev/null 2>&1; then
		DOCKER_CMD=(docker)
		return 0
	fi

	if sudo -n docker info >/dev/null 2>&1; then
		DOCKER_CMD=(sudo docker)
		return 0
	fi

	if command -v sudo >/dev/null 2>&1 && [ -t 0 ]; then
		echo "Docker-Zugriff ohne Gruppe erkannt. Verwende sudo docker (ggf. Passwortabfrage)."
		if sudo docker info >/dev/null 2>&1; then
			DOCKER_CMD=(sudo docker)
			return 0
		fi
	fi

	echo "[FEHLER] Kein Zugriff auf den Docker Daemon (/var/run/docker.sock)." >&2
	echo "Führe das Script mit sudo aus oder füge deinen User zur docker-Gruppe hinzu:" >&2
	echo "  sudo usermod -aG docker $USER" >&2
	echo "Danach neu einloggen und Script erneut starten." >&2
	exit 3
}

compose() {
	"${DOCKER_CMD[@]}" compose --env-file "$COMPOSE_ENV_FILE" "$@"
}

resolve_docker_cmd

echo "Stopping WEBSITE stack"
compose down

echo "Website stack stopped"
