#!/bin/bash

# Skript zum Testen von Datentraegern mit einem einfachen Schreib-Lesetest, mit protokollieren der benoetigten Zeit.
# Funktionert unter Linux (Ubuntu) und Cygwin.

# Dr. Rolf Freitag, 2017-01

# Simple version number (date of last coding)
VERSION=2017-01-25

# set -u : Stop the script when a variable isn't set (add -x for debugging)
set -u

# default command for badblocks program
badblockscommand=badblocks

# First: Check if the user is root. If not than usually the device can not be accessed if the user is not in the group disk.
#if [ $EUID -ne 0 ]
if [ $GROUPS -ne 0 ]
then
  echo
  echo "Warnung: Dieses Skript sollte generell von der Gruppe Root (Nr. 0) ausgeführt werden, aber ihre Benutzergruppe ist Nr. $GROUPS !"
  echo "Warning: This should generally be run from group root (Nr. 0), but your group is Nr. $GROUPS !"
  echo
  echo -n -e "\a"  # beep
  {
    dd if=/dev/urandom of=/dev/dsp bs=512 count=12 2>&1 >/dev/null # noise-beep
  }>/dev/null
  sleep 1
fi

# Second: Check the number of arguments.
if [ "$#" -ne 1 ]; then
  echo
  echo "Fehler: Falsche Anzahl ($#) Parameter. Bespiel: "$0" sdd. Ende."
  echo "Error: Illegal number ($#) of parameters. Example: "$0" sdd. Exiting."
  echo
  exit 2
fi

# Third: Check if the file does exist/is availible.
#fdisk -l /dev/"$2" | grep "$2" 2>&1 >/dev/null
# The fdisk -l does not work under Win7 64Bit in 2015, so /proc/partitions must be used instead.
cat /proc/partitions | grep "$1" 2>&1 >/dev/null
if [ $? -ne 0 ]; then
  echo
  echo "Fehler: Geraet /dev/$1 nicht gefunden. Ende."
  echo "Error: Device /dev/$1 not found; exiting."
  echo
  exit 4
fi

# Fourth: Check if the device/target is mounted, e. g. if it is the system drive.
# THIS USUALLY DOES NOT WORK WITH ENCRYPTED PARTITIONS/DRIVES!
mount | grep "/dev/$1" 2>&1 >/dev/null
if [ $? -eq 0 ]; then
  echo
  echo "Fehler: Geraet /dev/$1 ist scheinbar eingebunden (mounted). Ende."
  echo "Error: Device /dev/$1 seems to be mounted; exiting."
  echo
  exit 5
fi

echo -n "This script will do a write-read-test with device "
echo -n "/dev/$1"
echo "."
echo "Starting in 15 s (press <Ctrl>-C if you want to abort)."
echo "-"

# Show an partition overview
if [ "$(expr substr $(uname -s) 1 6)" == "CYGWIN" ]; then
  echo "output of cat /proc/partitions:"
  cat /proc/partitions
  badblockscommand=/usr/sbin/badblocks
else
  echo "output of lsblk:"
  lsblk
fi

echo
echo "Size of the (target) device $1:"
lsblk -b /dev/$1
echo

sleep 15
echo -n "Start date/time: "
date

# Write-Read-Test
time $badblockscommand -wsv -c 65536 -t random -o log_$1_`date +%F_%T`.txt /dev/$1 2>&1 | tee logg_$1_`date +%F_%T`.txt

if [ $? -ne 0 ]; then
  echo
  echo "Fehler: Siehe obige Fehlermeldung."
  echo "Error: Read the error message above."
  echo
  exit 6
fi

echo
echo -n "Erledigt, "; date
echo -n "Done, "; date
echo

exit 0
