#!/usr/bin/env bash
#Nifty: Perform iotests and gather basic system info
ce() {
  echo $(tput setaf 6)[INFO] $@$(tput sgr0)
}

eo() {
  echo $(tput setaf 1)[ERROR] $@$(tput sgr0)
}


ce "Checking all requirements"
requirements="cat grep fio ioping df dmidecode"
ok=true
for req in $requirements; do
	if ! command -v $req >/dev/null 2>&1 ; then
		eo "$req is not installed"
		ok=false
	fi
done

if [ $ok != true ]; then
	eo "Not all requirements met. Quitting"
	exit 1
fi


output="gather_output.txt"
if [ -f "$output" ]; then
	eo "$output file already exists. Please remove this file before running"
	exit 1
fi

ce "Checking free space"
space=$(df --output=avail -k . | sed '1d;s/[^0-9]//g')
if [ $space -lt 4500000 ]; then
	eo "Less than 4500000 kilobytes available on current disk. Cannot peform IO tests"
	exit 1
fi

ce "Running random rw io test (this might take a while)"

echo >> $output
echo >> $output
echo "### Random RW" >> $output
fio --randrepeat=1 --ioengine=libaio --direct=1 --gtod_reduce=1 --name=rwrand --filename=tbio.dat --bs=4k --iodepth=64 --size=4G --readwrite=randrw --rwmixread=75 >> $output

if [ -f "tbio.dat" ]; then
	ce "Cleaning up"
	rm -f tbio.dat
fi



ce "Running random read io test (this might take a while)"

echo >> $output
echo >> $output
echo "### Random read" >> $output
fio --randrepeat=1 --ioengine=libaio --direct=1 --gtod_reduce=1 --name=randread --filename=tbio.dat --bs=4k --iodepth=64 --size=4G --readwrite=randread >> $output

if [ -f "tbio.dat" ]; then
	ce "Cleaning up"
	rm -f tbio.dat
fi


ce "Running random write io test (this might take a while)"

echo >> $output
echo >> $output
echo "### Random read" >> $output
fio --randrepeat=1 --ioengine=libaio --direct=1 --gtod_reduce=1 --name=randwrite --filename=tbio.dat --bs=4k --iodepth=64 --size=4G --readwrite=randwrite >> $output

if [ -f "tbio.dat" ]; then
	ce "Cleaning up"
	rm -f tbio.dat
fi


ce "Testing disk latency"

echo >> $output
echo >> $output
echo "### ioping" >> $output
ioping -c 3 . >> $output


files="/proc/meminfo /proc/cpuinfo /proc/loadavg"

for file in $files; do
	ce "Saving contents of $file"
	echo >> $output
	echo >> $output
	echo "### Contents of $file" >> $output
	cat $file >> $output
done


ce "Saving disk sizing info"

echo >> $output
echo >> $output
echo "### df -h" >> $output
df -h >> $output


ce "Saving hardware info"

echo >> $output
echo >> $output
echo "### dmidecode" >> $output
dmidecode >> $output
