#!/bin/bash
# Created by: b2bde4
# Date (YYMMDD): 090609
# Link name: Guide Linux - Tips, tweaks and alignment
# Link: http://www.ocztechnologyforum.com/forum/showpost.php?p=396928&postcount=254

# Make this script executable before using, and run it as root.

# USAGE: sudo ./benchtest [Path]
# Eg:    sudo ./benchtest /dev/sda

# Number of bars in graph.
bar_length=30
# Graph limit in MB/s
max_speed=300
# Test block size in kB.
block_table=( 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 )
# Test file size in MB.
file_size=100

# n
do_bar ()
{
  echo -n [
  
  for (( i=0; i<$1 && i<bar_length; i++)); do
    echo -n =
  done
  
  for (( i; i<bar_length; i++)); do
    echo -n " "
  done
  
  echo -n ]
}

# speed, block_size
do_print ()
{
  a=$(( $1 * $bar_length / $max_speed ))
  printf "%8s" "[${2}kB]"
  do_bar $a
  echo "[${1}MB/s]"
}

# path, block_size
do_test ()
{ 
  count=$(( $file_size * 1024 / $2 ))
  
  var=$(dd conv=nocreat iflag=direct if=$1 of=/dev/null bs=${2}k count=$count 2>&1)
  
  start=-1;
  
  while [ "${var: $start : 1}" != " " ]
  do
    start=$(( $start-1 ))
  done
  
  start=$(( $start-1 ))
  stop=$start;
  
  while [ "${var: $start : 1 }" != " " ]
  do
    if [ ${var: $start : 1 } == "," ] || [ ${var: $start : 1 } == "." ]
    then
      stop=$(( $start-1 ))
    fi
    start=$(( $start-1 ))
  done
  
  start=$(( $start+1 ))
  
  return ${var: $start : $(( $stop - $start + 1 ))}
}

# Main.

if [ ! $1 ]
  then
  echo "Example: $0 [Path]"
  echo "         $0 /dev/sda"
  echo "Example: $0 [Path] [Graph limit (${max_speed}MB/s)]"
  echo "         $0 /dev/sda ${max_speed}"
  echo "Example: $0 [Path] [Graph limit (${max_speed}MB/s)] [Test file (${file_size}MB)]"
  echo "         $0 /dev/sda $max_speed $file_size"
  exit
fi

if [ $2 ]
  then
  max_speed=$2
fi

if [ $3 ]
  then
  file_size=$3
fi

echo "[block_size][%][read_speed]"
echo "Graph limit: ${max_speed}MB/s"
echo "Test file: ${file_size}MB"
echo ""

#printf "%9s%${bar_length}s\n" "0" "${max_speed}MB/s"

for i in ${block_table[@]}; do
  do_test $1 $i
  do_print $? $i
done  
