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

BACKUP_DIR="/mnt/s3bucket/nc-bk"

VOLUMES=(
  nextcloud_aio_apache
  nextcloud_aio_database
  nextcloud_aio_database_dump
  nextcloud_aio_mastercontainer
  nextcloud_aio_nextcloud
  nextcloud_aio_nextcloud_data
  nextcloud_aio_onlyoffice
  nextcloud_aio_redis
)

echo "🛑 Stopping all containers..."
docker stop $(docker ps -q) || true

for vol in "${VOLUMES[@]}"; do
    ARCHIVE="$BACKUP_DIR/${vol}.tar.gz"

    # Check if volume exists
    if docker volume inspect "$vol" >/dev/null 2>&1; then
        echo "📂 Volume $vol already exists"
    else
        echo "🆕 Creating volume $vol..."
        docker volume create "$vol" >/dev/null
    fi

    # Restore from archive if present
    if [ -f "$ARCHIVE" ]; then
        echo "♻️ Restoring $vol from $ARCHIVE..."
        docker run --rm \
          -v ${vol}:/volume \
          -v "$BACKUP_DIR":/backup \
          alpine sh -c "rm -rf /volume/* && tar -xzf /backup/${vol}.tar.gz -C /volume"
    else
        echo "⚠️ No archive found for $vol, skipping."
    fi
done

echo "🚀 Starting all containers..."
docker start $(docker ps -aq) || true

echo "✅ Restore complete and containers started!"
