#!/bin/bash
# secure-overwrite-files - Securely overwrite files with encrypted random data
# ⚠️  WARNING: THIS PERMANENTLY DESTROYS DATA - USE WITH EXTREME CAUTION
#
# Usage:
#   secure-overwrite-files --dry-run /path/to/files    # See what would happen
#   secure-overwrite-files /path/to/files              # Actually overwrite

set -euo pipefail

# Detect WSL and set compatibility flags
IS_WSL=false
if grep -qiE '(microsoft|wsl)' /proc/version 2>/dev/null || [ -n "${WSL_DISTRO_NAME:-}" ]; then
    IS_WSL=true
fi

# Colors for warnings
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

# Configuration
DRY_RUN=false
TARGET_DIR=""

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --help|-h)
            cat <<EOF
Secure File Overwriting Tool

Usage:
  $0 --dry-run /path/to/files    # Preview what would happen
  $0 /path/to/files               # Actually overwrite files

⚠️  WARNING: This PERMANENTLY DESTROYS data by overwriting with encrypted random noise.
   This is IRREVERSIBLE. Ensure you have backups before proceeding.

Safety Features:
  - Requires explicit directory path (won't work in current directory by accident)
  - Multiple confirmation prompts
  - Dry-run mode to preview actions
  - Skips system directories and hidden files
  - Shows file list before proceeding

Use Cases:
  - Overwriting sensitive files in cloud storage before deletion
  - Securely erasing data from external drives
  - Preparing media for disposal

EOF
            exit 0
            ;;
        *)
            TARGET_DIR="$1"
            shift
            ;;
    esac
done

# Validate target directory
if [ -z "$TARGET_DIR" ]; then
    echo -e "${RED}❌ ERROR: No target directory specified${NC}"
    echo "Usage: $0 [--dry-run] /path/to/files"
    echo "Run with --help for more information"
    exit 1
fi

if [ ! -d "$TARGET_DIR" ]; then
    echo -e "${RED}❌ ERROR: Directory does not exist: $TARGET_DIR${NC}"
    exit 1
fi

# Convert to absolute path
TARGET_DIR=$(cd "$TARGET_DIR" && pwd)

# Safety check: Don't allow certain dangerous paths
DANGEROUS_PATHS=(
    "/"
    "/home"
    "/etc"
    "/usr"
    "/var"
    "/bin"
    "/sbin"
    "/boot"
    "$HOME"
    "$HOME/.ssh"
    "$HOME/.gnupg"
)

for dangerous in "${DANGEROUS_PATHS[@]}"; do
    if [ "$TARGET_DIR" = "$dangerous" ]; then
        echo -e "${RED}❌ DANGER: Refusing to operate on system directory: $TARGET_DIR${NC}"
        echo "This would destroy your system!"
        exit 1
    fi
done

# Get list of files (skip hidden files and directories)
# Using portable array building that works on WSL, Linux, and any bash 3.2+
FILES=()
while IFS= read -r -d '' file; do
    FILES+=("$file")
done < <(find "$TARGET_DIR" -maxdepth 1 -type f ! -name ".*" -print0)

if [ ${#FILES[@]} -eq 0 ]; then
    echo -e "${YELLOW}⚠️  No files found in: $TARGET_DIR${NC}"
    exit 0
fi

# Display warnings and file list
echo ""
echo -e "${RED}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${RED}║  ⚠️  SECURE FILE OVERWRITE - IRREVERSIBLE DATA DESTRUCTION ║${NC}"
echo -e "${RED}╚════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${YELLOW}Target Directory:${NC} $TARGET_DIR"
echo -e "${YELLOW}Files to overwrite:${NC} ${#FILES[@]}"
if [ "$IS_WSL" = true ]; then
    echo -e "${YELLOW}Environment:${NC} WSL (Windows Subsystem for Linux)"
fi
echo ""
echo "The following files will be PERMANENTLY DESTROYED:"
echo ""

for file in "${FILES[@]}"; do
    filename=$(basename "$file")
    filesize=$(du -h "$file" | cut -f1)
    echo "  📄 $filename ($filesize)"
done

echo ""

if [ "$DRY_RUN" = true ]; then
    echo -e "${GREEN}🔍 DRY RUN MODE - No files will be modified${NC}"
    echo ""
    echo "What would happen:"
    echo "  1. Each file above would be overwritten with encrypted random data"
    echo "  2. Original content would be permanently destroyed"
    echo "  3. Files would remain with same names but contain only encrypted noise"
    echo ""
    echo "To actually perform this operation, run:"
    echo "  $0 $TARGET_DIR"
    echo ""
    exit 0
fi

# First confirmation
echo -e "${RED}⚠️  THIS WILL PERMANENTLY DESTROY ${#FILES[@]} FILES!${NC}"
echo ""
read -p "Are you ABSOLUTELY SURE you want to continue? Type 'YES' in all caps: " confirm1

if [ "$confirm1" != "YES" ]; then
    echo -e "${GREEN}✅ Aborted. No files were modified.${NC}"
    exit 0
fi

# Second confirmation with directory name
echo ""
echo -e "${RED}⚠️  FINAL CONFIRMATION${NC}"
echo "You are about to overwrite all files in:"
echo "  $TARGET_DIR"
echo ""
read -p "Type the full directory path to confirm: " confirm2

if [ "$confirm2" != "$TARGET_DIR" ]; then
    echo -e "${GREEN}✅ Aborted. Path did not match. No files were modified.${NC}"
    exit 0
fi

# Third confirmation - countdown
echo ""
echo -e "${RED}Beginning file destruction in:${NC}"
for i in 5 4 3 2 1; do
    echo "  $i..."
    sleep 1
done
echo ""

# Perform the overwriting
echo -e "${YELLOW}🔄 Overwriting files with encrypted random data...${NC}"
echo ""

SUCCESS_COUNT=0
FAIL_COUNT=0

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

    # Determine size in MB (minimum 1MB)
    size_mb=$(( (filesize / 1048576) + 1 ))
    if [ $size_mb -lt 1 ]; then
        size_mb=1
    fi

    printf "  📄 %s ... " "$filename"

    # Flush output immediately
    sync 2>/dev/null || true

    # Create encrypted random data with same name
    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

        # Verify temp file was created
        if [ ! -f "${file}.tmp" ]; then
            printf "${RED}✗ Failed (temp file not created)${NC}\n"
            ((FAIL_COUNT++)) || true
            continue
        fi

        # Replace original with encrypted noise (both variables fully quoted)
        if mv "${file}.tmp" "${file}"; then
            printf "${GREEN}✓ Destroyed${NC}\n"
            ((SUCCESS_COUNT++)) || true
        else
            printf "${RED}✗ Failed (mv error: $?)${NC}\n"
            ((FAIL_COUNT++)) || true
            rm -f "${file}.tmp" 2>/dev/null || true
        fi
    else
        printf "${RED}✗ Failed (encryption error)${NC}\n"
        ((FAIL_COUNT++)) || true
        rm -f "${file}.tmp" 2>/dev/null || true
    fi
done

echo ""
echo "═══════════════════════════════════════"
echo -e "${GREEN}✅ Complete${NC}"
echo "  Successfully destroyed: $SUCCESS_COUNT files"
if [ $FAIL_COUNT -gt 0 ]; then
    echo -e "  ${RED}Failed: $FAIL_COUNT files${NC}"
fi
echo ""
echo "⚠️  Original data is now PERMANENTLY UNRECOVERABLE"
echo "You can now delete these files from cloud storage."
echo ""
