#!/bin/sh
# Reset an HA Docker volume from a snapshot or fixture directory.
# Usage: reset.sh <compose_file> <service_name> <fixture_dir>
#
# Stops the service, clears and repopulates its volume from the fixture
# directory, then restarts.

set -e

COMPOSE_FILE="${1:?Usage: reset.sh <compose_file> <service_name> <fixture_dir>}"
SERVICE="${2:?}"
FIXTURE_DIR="${3:?}"
COMPOSE_DIR="$(dirname "$COMPOSE_FILE")"

printf 'Resetting %s from %s...\n' "$SERVICE" "$FIXTURE_DIR"

# Stop the service (keep the init container stopped too)
docker compose -f "$COMPOSE_FILE" stop "$SERVICE" 2>/dev/null || true

# Determine the volume name from compose project + service
VOLUME_NAME="$(docker compose -f "$COMPOSE_FILE" config --volumes 2>/dev/null | head -1)"
if [ -z "$VOLUME_NAME" ]; then
    printf 'Could not determine volume name from %s\n' "$COMPOSE_FILE" >&2
    exit 1
fi

# Wipe and repopulate the volume
docker run --rm \
    -v "$VOLUME_NAME":/config \
    -v "$(realpath "$FIXTURE_DIR")":/fixtures:ro \
    busybox \
    sh -c "rm -rf /config/.storage && cp -r /fixtures/. /config/"

# Restart the service
docker compose -f "$COMPOSE_FILE" start "$SERVICE"
printf 'Reset complete. Run wait-for-ha.sh to confirm readiness.\n'
