#!/bin/bash

# Script to extract metadata.json from mr_*.tar.gz files
# Skips if metadata.json already exists
# Usage: ./extract_metadata.sh

#set -e

METADATA_BASE="metadata"
mkdir -p "$METADATA_BASE"

extracted=0
skipped=0
failed=0

for tarfile in mr_*.tar.gz; do
    [ -e "$tarfile" ] || continue
    
    hash=$(basename "$tarfile" .tar.gz | sed 's/^mr_//')
    output_dir="$METADATA_BASE/$hash"
    output_file="$output_dir/metadata.json"
    
    # Skip if already exists
    if [ -f "$output_file" ]; then
        echo "⊙ Skipping $tarfile (already exists)"
        ((skipped++))
        continue
    fi
    
    mkdir -p "$output_dir"
    
    # Try to find and extract metadata.json at any depth
    if tar -tzf "$tarfile" 2>/dev/null | grep -q "metadata.json$"; then
        # Get the full path of metadata.json in the archive
        metadata_path=$(tar -tzf "$tarfile" 2>/dev/null | grep "metadata.json$" | head -1)
        
        # Extract it
        if tar -xzf "$tarfile" -O "$metadata_path" > "$output_file" 2>/dev/null; then
            echo "✓ $tarfile -> $output_file"
            ((extracted++))
        else
            echo "✗ Failed to extract from $tarfile"
            ((failed++))
        fi
    else
        echo "⊘ No metadata.json in $tarfile"
        ((failed++))
    fi
done

echo ""
echo "Summary: $extracted extracted, $skipped skipped, $failed failed/missing"
