#!/bin/bash

# @PREAMBLE_START@

# This section is copied from preamble.sh (automatically, during build) and
# should not be edited in place.

# turn on echo for debuging.
if [ ! -z "${VERT_DEBUG_PREAMBLE:-}" ]; then set -x; else set +x; fi
: '# Preamble begin'
: '# # Standardizing shell'
unset IFS # default word splitting on whitespace
set +o history # disable history. Should be default, but some reports otherwise
set -u # disallow unset variables

# note: these two vars are reset by vars.bash, but necessary to get there.
VERT_D=${VERT_VERT_D:-'/opt/vertica'}
BINLIB_D=${VERT_BINLIB_D:-"$VERT_D/share/binlib"}
source "$BINLIB_D/include/vars.bash"
source "$BINLIB_D/include/common_func.bash"
source "$BINLIB_D/include/self_vars.bash"

: '# Preamble end'
set +x # turn echo off
# @PREAMBLE_END@

function usage() {
    v_here_echo << HEREDOC
$SELF_SHORTNAME: Fix disk ioschedulers

Usage: 
   ./$SELF_SHORTNAME -v {noop,deadline} all        # fix all devices
   ./$SELF_SHORTNAME -v {noop,deadline} /dev/sda5  # by device name
   ./$SELF_SHORTNAME -v {noop,deadline} sda        # by /sys/block/\$device

Changes the ioscheduler for provided devices to the value specified.  IO
schedulers are per-block device, not per disk device, but this tool allows you
to specify block device or disk device.  In addition, 'all' may be specified.
HEREDOC
}

if [ "$EUID" != "0" ]; then
    # TODO: allow a non-root mode which omits blockdev size
    echo "Must be root. EUID = $EUID" >&2
    exit 1
fi

#
# Global vars
#
declare -a G_FIX_ITEMS
declare -a G_ALREADY_FIXED
declare -a G_WAS_FIXED
G_WAS_FIXED=()
G_ALREADY_FIXED=()
G_FIX_ITEMS=()
G_FIX_ALL=''

SCHEDULER=""
while getopts :v:h OPTVAL; do
    case "$OPTVAL" in
        h )
            usage
            exit 0
            ;;
        v )
            SCHEDULER="$OPTARG"
            if [ "$SCHEDULER" != "noop" -a "$SCHEDULER" != "deadline" ]; then
                echo "Invalid scheduler '$SCHEDULER'.  Must use 'noop' or 'deadline'" >&2
                exit 1
            fi
            ;;
        \? )
            echo "Invalid option: -$OPTARG" >&2
            exit 1
    esac
done

if [ -z "$SCHEDULER" ]; then
    echo "-v is required" >&2
    exit 1
fi

shift $(( OPTIND - 1 ))

G_FIX_ITEMS=("$@")

if [ "${#G_FIX_ITEMS[@]}" -lt 1 ]; then
    echo "No devices specified" >&2
    exit 1
fi

function should_fix() {
    local DEVICE="$1"
    local BLOCK="$2"

    local ITEM=""

    for ITEM in "${G_FIX_ITEMS[@]}"; do
        if [ "$ITEM" = "$DEVICE" ]; then
            return 0
        elif [ "$ITEM" = "$BLOCK" ]; then
            return 0
        elif [ "$ITEM" = "all" ]; then
            G_FIX_ALL='yes'
            return 0
        fi
    done

    return 1
}

function fix_iosched() {
    local BLOCK="$1"
    local VALUE="$2"

    G_WAS_FIXED+=("$BLOCK")

    if [ "${#G_ALREADY_FIXED[@]}" -gt 0 ]; then
        for ITEM in "${G_ALREADY_FIXED[@]}"; do
            if [ "$ITEM" = "$BLOCK" ]; then
                # echo "Already altered ioscheduler for $BLOCK" >&2
                return 0
            fi
        done
    fi


    echo "Changing ioscheduler on $BLOCK"
    if echo "$VALUE" > "$SYS_D/block/$BLOCK/queue/scheduler"; then
        G_ALREADY_FIXED+=("$BLOCK")
    else
        echo "Failed to alter IO scheduler on $BLOCK"
    fi
}

DISKS=`$BINLIB_D/read/get-disks`
# /dev/sda5,sda,256,deadline,ext4,4096
while IFS=, read -r DEV BLOCKDEV READAHEAD SCHEDULE FS BLOCKSZ LEFTOVERS; do
    if should_fix $DEV $BLOCKDEV; then
        fix_iosched "$BLOCKDEV" "$SCHEDULER"
    fi
done <<< "$DISKS"

if [ "${#G_WAS_FIXED[@]}" -lt "${#G_FIX_ITEMS[@]}" ]; then
    if [ -z "$G_FIX_ALL" ]; then
        echo "Some disks specified were not found on this machine"
        exit 2
    fi
fi
