#!/bin/bash
#
# Migrate NanoClaw filesystem layout from flat to tenant-scoped.
# Run this ONCE after deploying the multi-tenant code.
#
# Before: groups/general, data/ipc/general, data/sessions/general
# After:  groups/default/general, data/ipc/default/general, data/sessions/default/general
#
# Usage: ./scripts/migrate-to-multitenant.sh /path/to/nanoclaw/workdir
#

set -euo pipefail

WORKDIR="${1:-.}"
TENANT="${2:-default}"

echo "Migrating NanoClaw filesystem to multi-tenant layout"
echo "  Working directory: $WORKDIR"
echo "  Default tenant: $TENANT"
echo ""

migrate_dir() {
  local base="$1"
  local name="$2"

  if [ ! -d "$base/$name" ]; then
    echo "  SKIP: $base/$name (not found)"
    return
  fi

  # Already migrated?
  if [ -d "$base/$TENANT/$name" ]; then
    echo "  SKIP: $base/$TENANT/$name (already exists)"
    return
  fi

  echo "  MOVE: $base/$name -> $base/$TENANT/$name"
  mkdir -p "$base/$TENANT"
  mv "$base/$name" "$base/$TENANT/$name"
}

# Find group folder names from the groups/ directory
GROUPS_DIR="$WORKDIR/groups"
if [ -d "$GROUPS_DIR" ]; then
  for dir in "$GROUPS_DIR"/*/; do
    [ -d "$dir" ] || continue
    name=$(basename "$dir")
    # Skip if it looks like it's already a tenant dir (contains subdirs with logs/)
    if [ -d "$dir/logs" ] || [ -f "$dir/CLAUDE.md" ]; then
      migrate_dir "$GROUPS_DIR" "$name"
      migrate_dir "$WORKDIR/data/ipc" "$name"
      migrate_dir "$WORKDIR/data/sessions" "$name"
    else
      echo "  SKIP: $GROUPS_DIR/$name (doesn't look like a group folder)"
    fi
  done
else
  echo "No groups/ directory found"
fi

echo ""
echo "Migration complete. The DB migration happens automatically on next startup."
echo "Restart the nanoclaw service to apply."
