#! /usr/bin/bash

MOUNTPOINT='/mnt/speedtest'

# number of threads used during testing
nproc=4

if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit 1
fi

if [ "${1}" ]; then
 DEVICE=${1}
 PARTITION=${DEVICE}1
 echo "using device ${DEVICE}"
else
 echo "using default device ${DEVICE}"
fi

# check if sd card is inserted
if [ -e ${DEVICE} ]; then
  echo "card inserted"
else
  echo "no sd card found"
  exit 2
fi

echo "deleting partion #1"
sfdisk --delete -w ${DEVICE} 1 && sync

echo "creating new ext4 partition"
echo ",," |sfdisk ${DEVICE} && sync

echo "creating ext4 filesystem on ${PARTITION}"
echo "y" |mkfs.ext4 ${PARTITION}

#check if mount point is available, create otherwise
if [ ! -d "${MOUNTPOINT}" ]; then mkdir "${MOUNTPOINT}"; fi
mount -t ext4 "${PARTITION}" "${MOUNTPOINT}"
cd "${MOUNTPOINT}"
echo "preparing tests"
sysbench fileio --file-total-size=8G prepare > /dev/null

# Test with 16K block size, random read/write
echo "run test with 16K block size"
sysbench fileio --file-block-size=16K --file-total-size=8G --file-test-mode=rndrw --threads=$(nproc) run

# Test with 1M  block size, random read/write
echo "run test with 1M block size"
sysbench fileio --file-block-size=1M --file-total-size=8G --file-test-mode=rndrw --threads=$(nproc) run

# cleanup the test files
echo "cleaning up test files"
sysbench fileio --file-total-size=8G cleanup
cd - >/dev/null
umount ${PARTITION}


