#!/bin/bash
# DEBUG VERSION - Shows exactly what commands are being run
# Usage: secure-overwrite-files-debug /path/to/directory

set -euo pipefail
set -x  # Print every command before executing

TARGET_DIR="$1"

if [ ! -d "$TARGET_DIR" ]; then
    echo "ERROR: Not a directory: $TARGET_DIR"
    exit 1
fi

TARGET_DIR=$(cd "$TARGET_DIR" && pwd)

mapfile -t FILES < <(find "$TARGET_DIR" -maxdepth 1 -type f ! -name ".*")

echo "Found ${#FILES[@]} files:"
for file in "${FILES[@]}"; do
    echo "  - $file"
done

echo ""
echo "Processing files..."

for file in "${FILES[@]}"; do
    filename=$(basename "$file")
    filesize=$(stat -c%s "$file")

    size_mb=$(( (filesize / 1048576) + 1 ))
    if [ $size_mb -lt 1 ]; then
        size_mb=1
    fi

    echo ""
    echo "=== Processing: $filename ==="
    echo "    Full path: $file"
    echo "    Size: ${filesize} bytes"
    echo "    Will create: ${size_mb}MB encrypted file"
    echo "    Temp file: ${file}.tmp"

    echo -n "    Creating encrypted data... "
    if dd if=/dev/urandom bs=1M count=$size_mb 2>/dev/null | \
       gpg --symmetric --cipher-algo AES256 --batch \
       --passphrase "$(openssl rand -base64 32)" > "${file}.tmp" 2>/dev/null; then
        echo "✓"

        echo "    Temp file created:"
        ls -lh "${file}.tmp"

        echo -n "    Moving temp to final location... "
        echo "    Command: mv \"${file}.tmp\" \"${file}\""

        if mv "${file}.tmp" "${file}"; then
            echo "✓ SUCCESS"
            echo "    Final file:"
            ls -lh "$file"
        else
            echo "✗ FAILED"
            echo "    ERROR CODE: $?"
            ls -la "${file}.tmp" "$file" 2>&1 || true
        fi
    else
        echo "✗ FAILED to create encrypted file"
    fi
done

echo ""
echo "=== COMPLETE ==="
echo "Final directory state:"
ls -lah "$TARGET_DIR"
