#!/bin/bash

# Simple script to delete .wlz and .obj files older than their corresponding .nrrd files
# Usage: ./cleanup_old_derivatives_simple.sh [--dry-run] <base_directory>

DRY_RUN=false
TARGET_DIR=""

if [[ "$1" == "--dry-run" ]]; then
    DRY_RUN=true
    TARGET_DIR="$2"
else
    TARGET_DIR="$1"
fi

if [[ -z "$TARGET_DIR" ]]; then
    echo "Usage: $0 [--dry-run] <base_directory>"
    echo "Example: $0 --dry-run /data/VFB/i/"
    exit 1
fi

if [[ ! -d "$TARGET_DIR" ]]; then
    echo "Error: Directory '$TARGET_DIR' not found"
    exit 1
fi

TARGET_DIR="${TARGET_DIR%/}"

echo "Scanning: $TARGET_DIR"
[[ "$DRY_RUN" == true ]] && echo "[DRY RUN MODE]"
echo ""

# Find all .nrrd files and check if corresponding .wlz/.obj are older
find "$TARGET_DIR" -type f -name "*.nrrd" ! -name "*.dps.pkl.nrrd" | while read nrrd_file; do
    base_name="${nrrd_file%.*}"
    
    # Check .wlz
    wlz_file="${base_name}.wlz"
    if [[ -f "$wlz_file" ]] && [[ "$wlz_file" -ot "$nrrd_file" ]]; then
        if [[ "$DRY_RUN" == true ]]; then
            echo "[WOULD DELETE] $wlz_file"
        else
            rm -f "$wlz_file"
            echo "[DELETED] $wlz_file"
        fi
    fi
    
    # Check .obj
    obj_file="${base_name}.obj"
    if [[ -f "$obj_file" ]] && [[ "$obj_file" -ot "$nrrd_file" ]]; then
        if [[ "$DRY_RUN" == true ]]; then
            echo "[WOULD DELETE] $obj_file"
        else
            rm -f "$obj_file"
            echo "[DELETED] $obj_file"
        fi
    fi
done

