#!/bin/bash
# Migration script: move StoryCove Docker volume data to new NAS directories.
# Run this on the NAS as root (or with sudo) BEFORE restarting the stack.

set -euo pipefail

SRC_BASE="/volume1/@docker/volumes"
DST_BASE="/volume1/docker/storycove"

declare -A VOLUMES=(
  ["storycove_solr_data/_data"]="solr"
  ["storycove_postgres_data/_data"]="postgres"
  ["storycove_library_config/_data"]="config"
  ["storycove_images_data/_data"]="images"
  ["storycove_automatic_backups/_data"]="backups"
)

echo "=== StoryCove volume migration ==="
echo ""

# Verify source directories exist
for src_rel in "${!VOLUMES[@]}"; do
  src="$SRC_BASE/$src_rel"
  if [ ! -d "$src" ]; then
    echo "ERROR: Source directory not found: $src"
    exit 1
  fi
done

# Create destination directories if they don't exist
for dst_rel in "${VOLUMES[@]}"; do
  dst="$DST_BASE/$dst_rel"
  if [ ! -d "$dst" ]; then
    echo "Creating directory: $dst"
    mkdir -p "$dst"
  fi
done

echo ""
echo "Migrating data..."

for src_rel in "${!VOLUMES[@]}"; do
  dst_rel="${VOLUMES[$src_rel]}"
  src="$SRC_BASE/$src_rel"
  dst="$DST_BASE/$dst_rel"

  echo ""
  echo "  $src"
  echo "  -> $dst"

  rsync -a --info=progress2 "$src/" "$dst/"
done

echo ""
echo "Migration complete."
echo ""
echo "Old volume directories have NOT been deleted."
echo "Once you have verified the stack works correctly, you can remove them with:"
echo ""
for src_rel in "${!VOLUMES[@]}"; do
  echo "  rm -rf \"$SRC_BASE/$src_rel\""
done
echo ""
echo "Start the stack again with: docker compose up -d"
