#!/bin/bash
# ---------------------------------------------------------------------------
# loadtest - Write and read files of desired mountpoint

# Copyright 2016, Brett Kelly <bkelly@45drives.com>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

usage() {
        cat << EOF
Usage:
	loadtest [-a]

	-a	Run in auto mode. Without -c & -s specifed user input required
	-h	Show this summary 

EOF
        exit 0
}
datatest(){ #Launch Datatest. Writes & then Reads 6x 500GB File @ 1MB blocksize
	CHECK=$(df | grep zpool | awk '{print $1}')
	if [ ! -z $CHECK ];then
		for i in 1 2 3 4 5 6; do
			echo "Writing Test File $i"
            sync
			sudo dd if=/dev/zero of=/zpool/test$i bs=$1 count=$2 2>&1 | awk 'NR==3'
		done
		echo
		for i in 1 2 3 4 5 6; do
			echo "Reading Test File $i"
            echo 3 > /proc/sys/vm/drop_caches
			sudo dd if=/zpool/test$i of=/dev/null bs=$1 2>&1 | awk 'NR==3'
		done
	else
		echo "Pool Not Mounted"
	fi
}
cleanup(){ #Destroy pool and wipe drives
	echo -e "\nAll Done\nCleaning Up....."
	sudo zpool destroy zpool
	sudo wipedev -a
}
checkroot(){
	SCRIPT_NAME=$(basename "$0")
	if [ "$EUID" -ne 0 ];then
		echo "You must have root privileges to run $SCRIPT_NAME"
		exit 0
	fi
}

AUTO_MODE=yes
BLOCK_SIZE=1M
COUNT=500000
# FILE SIZE = BLOCK_SIZE*COUNT

while getopts 'ah' OPTION; do
	case ${OPTION} in
	a)
		AUTO_MODE=yes
		;;
	h)
		usage
		;;
	esac
done
if [ $# = 0 ];then
	usage
fi

checkroot

if [ $AUTO_MODE == yes ];then
	dmap -s 60
	zcreate -b -l raidz1 
    echo "STARTING WRITE/READ TEST"
	datatest $BLOCK_SIZE $COUNT
	cleanup
fi
