#!/bin/bash

# Backup Bridge Comparison Script
# Compares TO_SERVER staging area with Sam Storage and Archives
# Generates reports for MacBook assistant to know what's safe to remove

BRIDGE="/Volumes/Backup Bridge/TO_SERVER/Sam_Storage"
SAM_STORAGE="/Volumes/Sam Storage"
ARCHIVES="/Volumes/Archives"
REPORT_DIR="/Volumes/Sam Storage/backup_reports"
DATE=$(date +%Y%m%d_%H%M%S)

echo "=== BACKUP BRIDGE COMPARISON ==="
echo "Date: $(date)"
echo "Bridge: $BRIDGE"
echo "Sam Storage: $SAM_STORAGE"
echo "Archives: $ARCHIVES"
echo ""

# Create report files
SAFE_TO_DELETE="$REPORT_DIR/safe_to_delete_$DATE.txt"
NEEDS_MOVE="$REPORT_DIR/needs_move_to_server_$DATE.txt"
NEEDS_ARCHIVE="$REPORT_DIR/needs_archive_$DATE.txt"
SUMMARY="$REPORT_DIR/summary_$DATE.txt"

echo "Generating file lists..."

# Get all media files from Bridge staging area
echo "=== FILES IN BACKUP BRIDGE STAGING ===" > "$SUMMARY"
find "$BRIDGE" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.cr3" -o -iname "*.cr2" -o -iname "*.mp4" -o -iname "*.mov" \) -exec stat -f "%z %N" {} \; 2>/dev/null | sort > "$REPORT_DIR/bridge_files.txt"

echo "Bridge media files: $(wc -l < "$REPORT_DIR/bridge_files.txt")" >> "$SUMMARY"

# Get all media files from Sam Storage
find "$SAM_STORAGE" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.cr3" -o -iname "*.cr2" -o -iname "*.mp4" -o -iname "*.mov" \) -exec stat -f "%z %N" {} \; 2>/dev/null | sort > "$REPORT_DIR/sam_storage_files.txt"

echo "Sam Storage media files: $(wc -l < "$REPORT_DIR/sam_storage_files.txt")" >> "$SUMMARY"

# Compare by filename and size to find duplicates
echo "" >> "$SUMMARY"
echo "=== COMPARISON RESULTS ===" >> "$SUMMARY"

# Files that exist in both (safe to delete from MacBook)
echo "Finding duplicates (safe to delete from MacBook)..."
comm -12 <(awk '{print $1, $NF}' "$REPORT_DIR/bridge_files.txt" | sed 's|.*/||' | sort) \
         <(awk '{print $1, $NF}' "$REPORT_DIR/sam_storage_files.txt" | sed 's|.*/||' | sort) > "$SAFE_TO_DELETE"

echo "Duplicates (safe to delete): $(wc -l < "$SAFE_TO_DELETE")" >> "$SUMMARY"

# Files only in Bridge (need to move to server)
echo "Finding unique files (need to move to server)..."
comm -23 <(awk '{print $1, $NF}' "$REPORT_DIR/bridge_files.txt" | sed 's|.*/||' | sort) \
         <(awk '{print $1, $NF}' "$REPORT_DIR/sam_storage_files.txt" | sed 's|.*/||' | sort) > "$NEEDS_MOVE"

echo "Unique to Bridge (need move): $(wc -l < "$NEEDS_MOVE")" >> "$SUMMARY"

echo ""
echo "=== REPORTS GENERATED ==="
echo "Summary: $SUMMARY"
echo "Safe to delete: $SAFE_TO_DELETE"
echo "Needs move: $NEEDS_MOVE"
echo ""
cat "$SUMMARY"