#!/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@

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
#
# newline
NL="
"

function dbg() {
    # print a debug message to stderr if VERT_DEBUG_GET_DISKS is set
    if [ -z "${VERT_DEBUG_GET_DISKS:-}" ]; then
        return 0
    fi

    echo "dbg: $@" >&2
}

function has_comma() {
    # exit 0 if $1 has a comma in it.
    case "$1" in
        *,* )
            return 0
            ;;
        *)
            return 1
            ;;
    esac
}

function dependency_check() {
    if [ ! -d "$SYS_D/block" ]; then
        echo "Could not find $SYS_D/block directory. Cannot run." >&2
        exit 1
    fi

    if [ ! -f "$ETC_D/mtab" ]; then
        echo "Could not find $ETC_D/mtab file. Cannot run." >&2
        exit 1
    fi
}

################################################################################
# BLOCK DEVICES
################################################################################

G_BLOCK_DEVICES=""

# A list of all block devices by ID. G_BLOCK_DEVICES as a line per entry in
# `/dev/' that is a "block special" device and ends with a newline.  Each
# non-empty line is in this format:
#
# ID DEV
#
#   ID: The device ID, like 8:1 from `stat'
#
#   DEV: The device path, like /dev/sda1.  This is last in case there are any
#   special characters (spaces?) it can still be consumed by `read'.

function get_block_devices() {
    # Populates the global G_BLOCK_DEVICEs which has a line per block device.
    #
    # Returns successfully unless some error was encountered during information
    # retrieval.

    G_BLOCK_DEVICES="" # reset

    _add_block_devices "$DEV_D"

    return $?
}

function _add_block_devices() {
    # usage: get_block_devices_inner /dev
    #
    # Adds to the global G_BLOCK_DEVICEs which has a line per block device.
    # This is recursive into all sub directories which are not symlinks.
    #
    # Returns successfully unless some error was encountered during information
    # retrieval.

    local DEVICE_LIST="$1"

    local DEVD=""
    local MAJOR=""
    local MINOR=""
    local ID=""
    local RC=""

    for DEVD in "$DEVICE_LIST/"*; do
        if [ -L "$DEVD" ]; then
            # ignoring symlinks of all types
            continue
        fi

        if [ -d "$DEVD" ]; then
            # a directory. recurse.
            _add_block_devices "$DEVD"
            RC="$?"
            if [ "$RC" != "0" ]; then
                return "$RC"
            fi
        fi

        if [ ! -b "$DEVD" ]; then
            # not a block special device. move on
            continue
        fi

        # to find the device ID we use stat
        STATOUT=$("$BIN_STAT" --format "%t %T" "$DEVD")

        RCODE="$?"

        if [ "$RCODE" != "0" ]; then
            # no device identifier found???
            echo "Unable to stat $DEVICE (return code: $RCODE)" >&2
            exit 1
        fi

        read -r MAJOR MINOR <<< "$STATOUT"
        # stat prints these values in hex, but we want them in decimal
        MAJOR=$(printf "%d" "0x$MAJOR")
        MINOR=$(printf "%d" "0x$MINOR")
        ID="${MAJOR}:${MINOR}"

        G_BLOCK_DEVICES="${ID} ${DEVD}${NL}${G_BLOCK_DEVICES}"
    done
}

function find_block_device_by_id() {
    # usage: find_block_device_by_id 8:0
    #
    # Prints the fully qualified `/dev/' entry for the given device id.
    #
    # Requires `get_block_devices' first.
    #
    # Takes one device id (e.g. 8:1)
    #
    # Exits with rc=1 if unable to find an appropriate match.

    local DEVID="$1"
    local BDEVID=""
    local BDEV=""

    # Attempt to find by ID
    while read -r BDEVID BDEV; do
        if [ "$BDEVID" = "$DEVID" ]; then
            echo "$BDEV"
            return 0
        fi
    done <<< "$G_BLOCK_DEVICES"

    return 1
}

################################################################################
# MOUNTED FILESYSTEMS
################################################################################

G_MOUNTED_FS=""

# The disks found in /etc/mtab are used as a starting point, with some disks
# excluded (see `get_mounted_fs').  G_MOUNTED_FS has a line per filesystem and
# ends with a newline. Each non-empty line is in this format:
#
# ID PID FS DEV
#
#   ID: The device ID, like 8:1 from `stat'
#
#   PID: The device parent ID, like 8:0.  This is just the first part of the
#   device ID and the second part set to 0.
#
#   FS: The filesystem.  May be 'unknown' if it has special characters.
#
#   BLOCKSZ: The IO block size of the device from `stat'
#
#   DEV: The device path, like /dev/sda1.  This is last in case there are any
#   special characters (spaces?) it can still be consumed by `read'.

function get_mounted_fs() {
    # Populates the global G_MOUNTED_FS which has a line per disk (partition).
    #
    # Excludes filesystems mounted in `/media/' or any filesystem from a device
    # not in `/dev/'.
    #
    # Returns successfully unless some error was encountered during information
    # retrieval.

    G_MOUNTED_FS="" # reset to empty

    local DEVICE=""
    local MNTPT=""
    local DISCARD=""
    local STATOUT=""

    local MAJOR=""
    local MINOR=""
    local BLOCKSZ=""
    local ID=""
    local PID=""

    local RCODE=""

    while read -r DEVICE MNTPT FS DISCARD; do
        # mtab escapes things (e.g. spaces with \040)
        DEVICE=$(echo -n -e "$DEVICE")
        MNTPT=$(echo -n -e "$MNTPT")

        if [ -z "$DEVICE" -o "${DEVICE:0:5}" != "/dev/" ]; then
            # All disks are assumed to be in /dev/*
            continue
        fi

        if [ "${MNTPT:0:7}" = "/media/" ]; then
            # ignore media drives
            continue
        fi

        # to find the device ID we use stat
        STATOUT=$("$BIN_STAT" --format "%t %T %o" "$DEVICE")

        RCODE="$?"

        if [ "$RCODE" != "0" ]; then
            # no device identifier found???
            echo "Unable to stat $DEVICE (return code: $RCODE)" >&2
            exit 1
        fi

        read -r MAJOR MINOR BLOCKSZ <<< "$STATOUT"
        # stat prints these values in hex, but we want them in decimal
        MAJOR=$(printf "%d" "0x$MAJOR")
        MINOR=$(printf "%d" "0x$MINOR")
        ID="${MAJOR}:${MINOR}"
        PID="${MAJOR}:0"

        # file system handling
        #
        # XXX: commas are bad because the eventual output is supposed to be
        # comma-separated.  We don't know of any valid filesystems with a comma,
        # so lets just call that unknown.  We should probably do a replace or
        # escape of the comma instead.  Some day.
        if [ -z "$FS" ] || has_comma "$FS"; then
            FS="unknown"
        fi

        # prepend a line.
        G_MOUNTED_FS="${ID} ${PID} ${FS} ${BLOCKSZ} ${DEVICE}${NL}${G_MOUNTED_FS}"
    done < "$ETC_D/mtab"
}

################################################################################
# SYS BLOCK ENTRIES
################################################################################

G_SYS_BLOCK="" # see get_sys_block

# The entries found in /sys/block/* are used as a starting point.  See
# `get_sys_block' for details.  G_SYS_BLOCK has a line per entry and ends with a
# newline.  Each line has the following format:
#
# ID BLOCKDEV
#
#   ID: A device identifier, like 8:0. Taken from /sys/block/*/dev
#
#   BLOCKDEV: The device directory in /sys/block, like 'sda' for

function get_sys_block() {
    # populates G_SYS_BLOCK
    G_SYS_BLOCK=""  # reset

    local FQBLOCKD=""
    local BLOCKD=""
    local DEVID=""

    for FQBLOCKD in "$SYS_D/block/"*; do
        BLOCKD=$(v_basename "$FQBLOCKD")
        if [ ! -f "$SYS_D/block/$BLOCKD/dev" ]; then
            # no device identifier found???
            echo "Unable to determine device ID for $BLOCKD" >&2
            exit 1
        fi

        read -r DEVID < "$SYS_D/block/$BLOCKD/dev"

        # TODO: Could verify that DEVID looks like `X:Y' (X and Y are integers)
        # here, but unlikely to be a problem.

        G_SYS_BLOCK="${DEVID} ${BLOCKD}${NL}${G_SYS_BLOCK}"
    done
}

function find_sys_block_by_id() {
    # usage: find_sys_block_by_id 8:1 8:0
    #
    # Prints the directory name in `/sys/block/' by device id.
    #
    # Requires `get_sys_block' first.
    #
    # Takes two device ids: a specific device ID (e.g. 8:1) and a parent device
    # id (e.g. 8:0).  Attempts to match the specific device ID first, then falls
    # back to the parent device ID.
    #
    # Exits with rc=1 if unable to find an appropriate match.

    local DEVID="$1"
    local PDEVID="$2"
    local BDEVID=""
    local BDEV=""

    # Attempt to find by ID
    while read -r BDEVID BDEV; do
        if [ "$BDEVID" = "$DEVID" ]; then
            echo "$BDEV"
            return 0
        fi
    done <<< "$G_SYS_BLOCK"

    # Attempt to find by PID (parent device ID)
    while read -r BDEVID BDEV; do
        if [ "$BDEVID" = "$PDEVID" ]; then
            echo "$BDEV"
            return 0
        fi
    done <<< "$G_SYS_BLOCK"

    return 1
}

function sys_block_scheduler () {
    # usage: sys_block_scheduler sda
    #
    # Prints the scheduler (or empty string) for a given entry in `/sys/block'.
    #
    # Exits with rc=1 only if a scheduler file exists, but it didn't have any
    # content which could be interpretted as a scheduler.  Still prints the
    # empty string in that scenario.

    local DEVICE="$1"
    local SCHEDFILE="$SYS_D/block/$DEVICE/queue/scheduler"

    if [ ! -f "$SCHEDFILE" ]; then
        echo ""
        return 0
    fi

    # Searching for the entry with brackets around it.  Start by sucking in the
    # entire file into SCHEDULING as an array of words
    local POLICY=""
    local SCHEDULING=()
    read -r -d '' -a SCHEDULING < "$SCHEDFILE"

    for POLICY in "${SCHEDULING[@]}"; do
        case "$POLICY" in
            \[*\] )
                POLICY="${POLICY:1:${#POLICY}-2}" # drop first and last
                echo "$POLICY"
                return 0
                ;;
            * )
                ;;
        esac
    done

    # If there was only one entry in the output, sometimes it won't be
    # surrounded by square brackets.  Nevertheless, that's the answer.
    if [ "${#SCHEDULING[*]}" -eq "1" ]; then
        echo "${SCHEDULING[0]}"
        return 0
    fi

    echo "Unable to determine active scheduling policy for $DEVICE" >&2
    echo "" # the empty string we promised.
    return 1
}

function print_device_info() {
    local DEVID=""
    local PDEVID=""
    local DEV=""
    local BDEV=""
    local READAHEAD=""
    local SCHEDULER=""
    local BLOCKSZ=""
    local PDEVICE=""

    echo "#device,parent_device,/sys/block,readahead,fs,blocksz"
    while read -r DEVID PDEVID FS BLOCKSZ DEV; do
        if [ -z "$DEV" ]; then
            continue
        fi

        READAHEAD=$("$BIN_BLOCKDEV" --getra "$DEV")

        # FIXME: This doesn't actually work. On a VM, we found /dev/sdb had a
        # parent of /dev/sda which was incorrect. Commenting this out for now.
        # Feel free to delete it at a later point in time if no one's come back
        # with a better solution - drice Jan 2014
        #PDEVICE=$(find_block_device_by_id "$PDEVID")

        BDEV=$(find_sys_block_by_id "$DEVID" "$PDEVID")

        if [ -z "$BDEV" ]; then
            echo "Unable to find block device for $DEV." >&2
            SCHEDULER=""
        else
            SCHEDULER=$(sys_block_scheduler "$BDEV")
        fi

        #echo "$DEV,$PDEVICE,$BDEV,$READAHEAD,$SCHEDULER,$FS,$BLOCKSZ"
        echo "$DEV,$BDEV,$READAHEAD,$SCHEDULER,$FS,$BLOCKSZ"
    done <<< "$G_MOUNTED_FS"
}

dependency_check

get_mounted_fs
dbg "G_MOUNTED_FS:
$G_MOUNTED_FS"

get_sys_block
dbg "G_SYS_BLOCK:
$G_SYS_BLOCK"

# See previous FIXME comment
#get_block_devices
#dbg "G_BLOCK_DEVICES:
#$G_BLOCK_DEVICES"

print_device_info
