#!/bin/bash

set -euo pipefail

# === CONFIGURAÇÕES ===
DEVICE="/dev/sdi"
BLOCK_SIZE=4096
BLOCK_COUNT=$(($(sudo blockdev --getsize64 "$DEVICE") / BLOCK_SIZE))
BATCH_SIZE=100000  # Reduzido ainda mais para minimizar riscos e facilitar retomadas
PROGRESS_DIR="/bad"
PROGRESS_FILE="$PROGRESS_DIR/progress.txt"
BADBLOCKS_FILE="$PROGRESS_DIR/badblocks.txt"
MOUNT_POINT="/sea"

mkdir -p "$PROGRESS_DIR"

# === RECUPERA PROGRESSO ANTERIOR OU INICIA DO ZERO ===
if [[ -f "$PROGRESS_FILE" ]]; then
  START_BLOCK=$(cat "$PROGRESS_FILE")
else
  START_BLOCK=0
  echo 0 > "$PROGRESS_FILE"
fi

# === LOOP INCREMENTAL ===
echo "Iniciando varredura incremental de badblocks em $DEVICE"
echo "Tamanho total do disco: $BLOCK_COUNT blocos"
echo "Iniciando em: $START_BLOCK"

while [[ $START_BLOCK -lt $BLOCK_COUNT ]]; do
  END_BLOCK=$((START_BLOCK + BATCH_SIZE))
  [[ $END_BLOCK -gt $BLOCK_COUNT ]] && END_BLOCK=$BLOCK_COUNT

  COUNT=$((END_BLOCK - START_BLOCK))
  echo "Verificando blocos de $START_BLOCK a $((END_BLOCK - 1))..."

  sudo badblocks -nsv -b $BLOCK_SIZE -c 1024 -o "$PROGRESS_DIR/temp_badblocks_$START_BLOCK.txt" "$DEVICE"

  cat "$PROGRESS_DIR/temp_badblocks_$START_BLOCK.txt" >> "$BADBLOCKS_FILE"
  rm -f "$PROGRESS_DIR/temp_badblocks_$START_BLOCK.txt"

  START_BLOCK=$END_BLOCK
  echo $START_BLOCK > "$PROGRESS_FILE"
done

# === CRIAR SISTEMA DE ARQUIVOS EXT4 IGNORANDO BADBLOCKS ===
echo "Criando sistema de arquivos ext4 ignorando setores defeituosos..."
sudo mkfs.ext4 -L SEA -l "$BADBLOCKS_FILE" "$DEVICE"

# === MONTAGEM ===
echo "Montando em $MOUNT_POINT..."
sudo mkdir -p "$MOUNT_POINT"
sudo mount "$DEVICE" "$MOUNT_POINT"
echo "Disco montado com sucesso em $MOUNT_POINT."

echo "Processo concluído com sucesso."
