#!/bin/sh
# (c) 2010 Aleksander Adamowski
# This script benchmarks various GPT partition offsets
# in order to find an optimal one for performance.
#
# Written for optimal partitioning of my new 4 kB sector
# Western Digital Advanced Format HDD (WD15EARS).
#

warning="WARNING!!!
This script completely erases significant portions of the configured block 
device (the \"device\" variable specified in its body).

Shoots first, asks questions later.

In order to certify that you know what you're doing and accept that you WON'T 
HOLD THE AUTHOR OF THIS SCRIPT LIABLE FOR ANY DAMAGES THAT IT MIGH CAUSE,
you have to modify the script by removing  or commenting out the \"exit 5\" 
command that prevents it from running.
EOD"

echo "$warning"

exit 5

# Here begins the actual script logic
device=sdb
export LANG=C

# part_offset in sectors (512B unless the device reports other size to parted):
part_offset=41

for part_offset in $(seq 41 64); do
    umount /mnt/${device}1
    parted /dev/$device unit s rm 1
    sleep 1
    parted_out="$(parted -s /dev/$device unit s "mkpart primary ext2 $part_offset -1")"
    if [ $? -ne 0 ]; then
        echo "Parted error:"
        echo "$parted_out"
        last_sector="$(echo "$parted_out" | fgrep 'closest location we can manage' | perl -e '$_ = <>; if ($_ =~ /to ([0-9]+)s./) { print $1; }' )"
        echo "Last possible partition sector:"
        echo "[$last_sector]"
        parted_out="$(parted -s /dev/$device unit s "mkpart primary ext2 $part_offset $last_sector")"
        if [ $? -ne 0 ]; then
            echo "FATAL ERROR: could not determine proper sector range for new partition:"
            echo "$parted_out"
            exit 1
        fi
    fi
    sleep 1
    parted /dev/$device unit s print | tee -a "parted_dev_${device}_partition_at_${part_offset}s.txt"
    sync
    mkfs.ext4 -T largefile4 /dev/${device}1
    mount /dev/${device}1 /mnt/${device}1
    ls -la /mnt/${device}1
    cat /proc/partitions  | egrep "($device|major)" > "proc_partitions_${device}_start_at_${part_offset}s.txt"
    sync
    sleep 1
    echo "Executing postmark-quick with partition offset $part_offset:"
    postmark postmark-quick.conf | tee -a "postmark-quick_${device}_${part_offset}.txt"

    echo "Sleeping 5 seconds..."
    sleep 5
done

