# Copyright (C) 2014 McAfee, Inc.  All Rights Reserved.
#
# helpers for disk subsystem firmware updates
#
# work out where I live
if [[ -n $BASH_SOURCE ]] ; then
    # if bash source is present use that
    __mydir=$(dirname $(readlink -f $BASH_SOURCE))
else
    # otherwise guess from $0 (busybox)
    __mydir=$(dirname $(readlink -f $0))
    __mydir=${__mydir%/getlogs}/utils
    [[ -d $__mydir ]] || {
        echo "Cannot work out directory for utilities" >&2
        exit 1
    }
fi

# remember the OS idea of PATH
osPATH="$PATH"

# Source function library.
PATH=$__mydir:$PATH

# we always put the 32 bit binaries onto the library path
# since some binaries are 32 bit only
PATH=$__mydir/../bin32:$PATH
LD_LIBRARY_PATH=$__mydir/../lib32:$LD_LIBRARY_PATH

# set binary and library paths as well
if [[ $(uname -m) = x86_64 ]] ; then
    PATH=$__mydir/../bin64:$PATH
    LD_LIBRARY_PATH=$__mydir/../lib64:$LD_LIBRARY_PATH
fi
export PATH
export LD_LIBRARY_PATH

# ensure that we have a good temporary working directory
if [[ -n $LDTLOGDIR ]] ; then
    export TMPDIR=$LDTLOGDIR
elif [[ -z $TMPDIR ]] ; then
    export TMPDIR=/tmp
fi

# some environments do not have tput
# just ignore it
if ! type -p tput >/dev/null ; then
    function tput () { true ; }
fi

# use the getlogs version of timeout since we can fiddle with that
tmocmd=TimeOut

# see if there is a timeout set
# use a default 180 seconds if unset
LDTTIMEOUT=${LDTTIMEOUT:-180}
if [[ $LDTTIMEOUT = 0 ]] ; then
    # we've been told not to do timeouts
    tmo=
    tmocmd=
else
    # use the available timeout wrapper
    tmo="do_timeout $LDTTIMEOUT"
fi

# sometimes we find permissions have been lost en route
chmod a+x $__mydir/../*/* 2>/dev/null

# the HDD stuff needs the sg module loaded
modinfo sg >/dev/null 2>&1 && modprobe sg

#########################################################################
#
# general utilities

# some platforms do not have mktemp
type -p mktemp >/dev/null 2>&1 || {
    function mktemp () {
        local path=
        local isdir=
        local e=0
        local mk=
        while [[ -n $1 ]] ; do
            if [[ $1 = -t ]] ; then
                path=$TMPDIR
                [[ -n $TMPDIR ]] || path=/tmp
                shift
                continue
            fi
            if [[ $1 = -p ]] ; then
                path="$2"
                shift 2
                continue
            fi
            if [[ $1 = -d ]] ; then
                isdir=1
                shift
                continue
            fi
            mk=${path:+$path/}${1%.X*}.$RANDOM
            if [[ -n $isdir ]] ; then
                mkdir -p "${mk}" && chmod 700 "${mk}" || ((e|=$?))
            else
                touch "${mk}" && chmod 600 "${mk}" || ((e|=$?))
            fi
            echo "$mk"
            exit $e
        done
    }
}

# some platforms do not have a tr that understands [:print:]
function printable () {
    if type -p sed >/dev/null 2>&1 ; then
        sed -e 's/[^[:print:]]//' $1
    elif type -p tr >/dev/null 2>&1 ; then
        tr -dc '[:print:]' <$1
    else
        cat $1
    fi
}

# wrapper around the timeout handler to ensure that the command is run
# with no buffering on its output so that if it is killed, no output
# is lost
# p1=timeout
# p2... = cmd to run
do_timeout()
{
    local t=$1
    shift
    if type -p stdbuf >/dev/null ; then
        $tmocmd $t stdbuf -o 0 -e 0 "$@"
    elif type -p script >/dev/null && ! script -h 2>&1 | grep -q 'cannot open' ; then
        # NDLP script is broken...
        $tmocmd $t script -q -c "$*" -a -f /dev/null
    else
        # fallback - might loose data if timeout kicks in
        $tmocmd $t "$@"
    fi
}

TimeOut()       # run a command but kill if it takes too long
{
    local log=echo
    local e=
    [[ $1 == -l ]] && { log="logger -t ${0##*/}"; shift; }
    local time=$1       # first arg is the max time to run
    shift               # rest are the command
    (
        trap '[[ $! -ne $p ]] && kill $!' EXIT
        "$@" <&0 &      # start command in background
        local p=$!  # pid of command
        exec 2>/dev/null
        (   # assasin will sleep a time then kill command if still running
            set -e
            trap '[[ $! -ne $p ]] && kill $!' EXIT TERM HUP
            sleep $time >/dev/null & wait $!
            kill -0 $p
            $log "$1 taking too long - killing it" || true
            kill $p
            sleep 1 >/dev/null & wait $!
            kill -9 $p
            exit 124
        ) </dev/null &
        wait $p             # wait for command to finish or be killed
        local err=$?        # collect its exit code
        kill -HUP $!        # sighup the sleeping assasin
        kill $!             # kill the sleeping assasin
        wait $! || [[ $? -ne 124 ]] || err=124
        return $err
    )
    e=$?
    [[ $e -ne 255 ]] || exit $err
    return $e
}

# helper to remove dos line endings
strip_crlf () {
    awk 'BEGIN{RS="(\n|\r\n)"}{printf "%s\n",$0}' "$@"
}

echo_passed() {
    tput hpa 60
    echo -n '['
    tput setf 6
    echo -n "PASSED"
    tput setf 9
    echo -ne ']\r'
    return 1
}
echo_success() {
    tput hpa 60
    echo -n '['
    tput setf 2
    echo -n "  OK  "
    tput setf 9
    echo -ne ']\r'
    return 1
}
echo_failure() {
    tput hpa 60
    echo -n '['
    tput setf 4
    echo -n "FAILED"
    tput setf 9
    echo -ne ']\r'
    return 1
}

#########################################################################
#
# Utilities for ipmitool

# libcrypto in ipmitool causes us issues
ipmitool=`type -p ipmitool`
have_ipmitool=1
ldd $ipmitool 2>/dev/null | while read lib x status ; do
    [[ $status == not\ found ]] || continue
    lib2=${lib%.so*}
    find /lib64 /usr/lib64 /usr/local/lib64 -name "${lib2}*" -and -type f | head -1 | xargs -i -r ln -snf {} $__mydir/$lib
done

# if we haven't managed to make our ipmitool work then attempt to use
# the system one if available
if ldd $ipmitool 2>/dev/null | grep -q 'not found' ; then
    if ! ipmitool=$(PATH="$osPATH" type -p ipmitool 2>/dev/null) ; then
        echo "Failed to find a usable ipmitool command, no BMC data will be retrieved." >&2
        ipmitool="echo no ipmitool:"
        have_ipmitool=
    fi
fi

# ipmitool wrapper to invoke the script which avoids querying
# software owned sensors, since that causes problems for some
# BMCs
# since some BMCs are still dodgy, we also add a timeout wrapper
# around the ipmitool call
fixedsdr=${TMPDIR:-/tmp}/ipmi_sdr_fixed
rm -f $fixedsdr
ipmitool () {
    if [[ -z $have_ipmitool ]] ; then
        # just exit cleanly if no ipmitool
        return 0
    fi
    # if the caller specifies an SDR file then use that
    # also if the caller requests an sdr dump
    if [[ " $@ " = *\ -S\ * || " $@ " = *\ sdr\ dump\ * ]] ; then
        # just run what was requested, trust the caller
        $tmo $ipmitool "$@"
    else
        # the fixed up cache file name
        local sdr=$fixedsdr

        # if the cache file doesn't exist then generate it
        if [[ ! -s $sdr ]] ; then
            $__mydir/ipmi_fix_sdr $sdr
            # if we fail to generate the fixed file then don't pass it to ipmitool
            [[ -s $sdr ]] || sdr=
        fi

        $tmo $ipmitool "$@" ${sdr:+-S $sdr}
    fi
    local e=$?
    # do not record exit code if this is a raw command
    [[ "$*" = *dump* || "$*" = *writeraw* ]] || echo "EXITCODE $e"
    return $e
}

#########################################################################
#
# Utilities for megaraid controllers

if [[ $(uname -m) = x86_64 ]] ; then
    cmdtool2=CmdTool264
else
    cmdtool2=CmdTool2
fi

# awk script to parse RAID controller PCI info and kernel PCI view
# into a simple map of scsi hostN to aM for megacli command
a_megacli_map='
/Controller /{
    a=$NF
}
/Bus Number/{
    b=strtonum("0x"$NF)
}
/Device Number/{
    d=strtonum("0x"$NF)
}
/Function Number/{
    adap[sprintf("0000:%02x:%02x.%x",b,d,strtonum("0x"$NF))]=a
}
/sys.bus.pci.drivers.megaraid/{
    split($0,h,"/")
    if (h[7] in adap){
        printf "%s %s %s\n",h[8],h[7],adap[h[7]]
    }
}'

# convert hostN to aM for megacli command
megaraidmap=${TMPDIR}/megaraid_map.txt
rm -f $megaraidmap

megacli_map () {
    if [[ ! -s ${megaraidmap} ]] ; then
        # cache a mapping from hostX to aY
        {
            $cmdtool2 adpgetpciinfo aall nolog
            printf "%s\n" /sys/bus/pci/drivers/megaraid*/0*/host*
        } | awk "$a_megacli_map" > ${megaraidmap}
    fi
    # look the host number up in the map file
    awk -v h=${1##*/} 'BEGIN{a=99}($1==h){a=$NF}END{print a;if(a==99){exit 1};exit 0}' ${megaraidmap}
}

# wrapper around megacli/cmdtool2
# first arg is hostN
megacli () {
    local host=$1
    shift
    if [[ -n $DEBUGDIR ]] ; then
        # in debug mode we return the results of the pre-canned query
        local arg=${1#-}
        if [[ -e $DEBUGDIR/$arg.txt ]] ; then
            dos2unix <$DEBUGDIR/$arg.txt
        elif [[ $arg == pdgetmissing && -e $DEBUGDIR/pdmissing.txt ]] ; then
            dos2unix <$DEBUGDIR/pdmissing.txt
        elif [[ $arg == adpeventlog && -e $DEBUGDIR/eventlog2.txt ]] ; then
            dos2unix <$DEBUGDIR/eventlog2.txt
        else
            # otherwise we echo the command and pretend it worked
            echo ">>> megacli $1 $*"
        fi
        return 0
    fi
    # map PCI ID to aN
    # assume ordered by PCI bus order
    adapter=$(megacli_map $host)
    [[ -n $adapter || $adapter -ne 99 ]] || {
        : failed to find adapter number of $host
        return 1
    }

    $cmdtool2 "$@" a$adapter nolog 2>&1
}

# check megaraid HDD state
# p1=hostN
# p2=e:s
megaraid_drive_state() {
    megacli $1 pdinfo physdrv "[$2]" | awk 'BEGIN{FS="[[:space:]]*: ";s="Unknown";e=1}($1=="Firmware state"){s=$2;e=0;exit}END{print s;exit e}'
}

#########################################################################
#
# Utilities for mptstatus wrapper
mptmap=${TMPDIR}/mpt_map.txt
rm -f $mptmap

# p1=hostN
mpt_map () {
    if [[ ! -s $mptmap ]] ; then
        # create the map from ioc number to host
        printf "%s\n" /sys/module/mptsas/drivers/pci:mptsas/0*/host* | awk 'BEGIN{FS="/";ioc=0}{printf "%d %s\n",ioc++,$NF}' >$mptmap
    fi
    awk -v h=${1##*/} 'BEGIN{ioc=99}($2==h){ioc=$1;exit}END{print ioc}' $mptmap
}

# p1=hostN
# p... = args
mptstatus () {
    local ioc=$(mpt_map $1)
    if [[ -z $ioc || $ioc -eq 99 ]] ; then
        : failed to find adapter number of $host
        return 1
    fi
    shift
    mpt-status -u $ioc "$@"
}


#########################################################################
#
# Utilities for isdct1 wrapper
# isdct v1 is used for i910 SSDs only
# shares mpt2sas raid controller

# p1=hostN
i910_map () {
    local d=
    local e=
    local l=
    if [[ -z $i910_tidy || ! -d /dev/disk/by-id ]] ; then
        # set up the necessary stuff for isdct to work
        # TODO put this into a chroot
        # (some products make a chroot impossible)
        mkdir -m 755 -p /dev/disk/by-id
        while read d ; do
            e=$(scsi_id  --whitelisted --device=/dev/${d##*/} )
            [[ -z $e ]] || {
                l=/dev/disk/by-id/scsi-$e
                [[ -e $l ]] || {
                    ln -snf ../../${d##*/} $l
                    i910_tidy="${i910_tidy}$l "
                }
            }
        done < <(printf "%s\n" /sys/block/sd* )
        [[ -c /dev/mpt2ctl ]] || {
            mknod -m 644 /dev/mpt2ctl c $(sed -e 's/:/ /' /sys/devices/virtual/misc/mpt2ctl/dev)
            i910_tidy="${i910_tidy}/dev/mpt2ctl "
        }
    fi
    mpt2_map "$@"
}

# p1=hostN
# p... = args
Isdct1 () {
    local ioc=$(i910_map $1)
    if [[ -z $ioc || $ioc -eq 99 ]] ; then
        : failed to find adapter number of $host
        return 1
    fi
    shift
    isdct1 -device $ioc "$@"
}

check_restore_i910 () {
    # see if we have to tidy up the i910 nodes we may have created
    [[ -n $i910_tidy ]] && rm -f $i910_tidy
}

#########################################################################
#
# Utilities for sas2ircu wrapper
mpt2map=${TMPDIR}/mpt2_map.txt
rm -f $mpt2map

# p1=hostN
mpt2_map () {
    if [[ ! -s $mpt2map ]] ; then
        # create the map from ioc number to host
        # newer kernels merge mpt2sas into mpt3sas so have to try both...
        if [[ -e /sys/module/mpt2sas ]] ; then
            printf "%s\n" /sys/module/mpt2sas/drivers/pci:mpt2sas/0*/host*
        else
            printf "%s\n" /sys/module/mpt3sas/drivers/pci:mpt3sas/0*/host*
        fi | awk 'BEGIN{FS="/";ioc=0}{printf "%d %s\n",ioc++,$NF}' >$mpt2map
    fi
    awk -v h=${1##*/} 'BEGIN{ioc=99}($2==h){ioc=$1;exit}END{print ioc}' $mpt2map
}

# p1=hostN
# p... = args
Sas2ircu () {
    local ioc=$(mpt2_map $1)
    if [[ -z $ioc || $ioc -eq 99 ]] ; then
        : failed to find adapter number of $host
        return 1
    fi
    shift
    sas2ircu $ioc "$@"
}


#########################################################################
#
# Utilities for smartctl

find_smartctl () {
    smartctl=$(type -p smartctl)
    $smartctl -V 2>&1 | grep -q smartmontools || {
        # seems like the one on the path (likely ours) does not run
        # likely because 32 bit libs are missing
        # see if there is an OS version we can use
        smartctl=$(
            PATH="$osPATH"
            type -p smartctl 2>/dev/null
        )
        [[ -n $smartctl ]] || smartctl=none
    }
}
# p1=-d argument to smartctl
# p2=block device 
# p*=smartctl args
Smartctl () {
    local d="$1"
    local b="$2"
    local e=0
    shift 2
    [[ -n $smartctl ]] || find_smartctl
    if [[ $smartctl != none ]] ; then
        $smartctl --drivedb=/dev/null "$@" ${d:+-d $d} $b
        e=$?
        echo "EXITCODE $e"
    else
        echo "smartctl missing"
    fi
    return $e
}

# smartctl wrapper to run against a megaraid host
# p1=hostN
# p2=controllerType
# p3=drive ID (from getDrives - eEEsSSdPD)
# p*=commands
SmartctlHost_megaraid () {
    local h=$1
    local c=$2
    local d=$3
    shift 3
    Smartctl megaraid,${d##*d} /dev/bus/${h##*/host} "$@"
}

# smartctl wrapper to run against a scsi_host
# p1=hostN
# p2=controllerType
# p3=drive ID (from getDrives - eEEsSSdPD)
# p*=commands
SmartctlHost () {
    local h=$1
    local c=$2
    local d=$3
    shift 3
    if [[ $(type -t "SmartctlHost_$c") = function ]] ; then
        SmartctlHost_$c "$h" "$c" "$d" "$@"
    elif [[ $d = [0-9]* ]] ; then
        # the drive ID is the target within the host which we must remap
        # to /dev/sg*
        d=$(shopt -s nullglob ; echo $h/device/port*/end_device-*/target*/*:*:$d:*/scsi_generic/* | head -1)
        Smartctl "" /dev/${d##*/} "$@"
    else
        # everything else uses smartctl without funky arguments
        Smartctl "" /dev/$d "$@"
    fi
}


#########################################################################
#
# Firmware Revision checkers

# helpers to retrieve the latest firmware rev for each controller type
get_fwrev_megaraid() {
    {
        if [[ -n $CONTROLLERDIR ]] ; then
            [[ -s $CONTROLLERDIR/adpallinfo.txt ]] && strip_crlf $CONTROLLERDIR/adpallinfo.txt
        else
            megacli $1 adpallinfo
        fi
    } | sed -n -e 's/FW Package Build: //p'
}
# mptsas has lots of firmware versions in one release
# we just report on the two critical ones from /proc
get_fwrev_mptsas() {
    if [[ -n $CONTROLLERDIR ]] ; then
        [[ -s $CONTROLLERDIR/sasflash.txt ]] && awk 'BEGIN{RS="(\n|\r\n)"}/BIOS Version/{b=$NF}/Firmware Version/{f=$NF}END{printf "%s-%s\n",f,b}' $CONTROLLERDIR/sasflash.txt
    else
        awk '{if (x!="") {x=x"-"} ; x=x gensub(/\.00\.00$/,"",1,$0)}END{print x}' $1/version_{fw,bios}
    fi
}
# mptsas has lots of firmware versions in one release
# we just report on the two critical ones from /proc
get_fwrev_mpt2sas() {
    if [[ -n $CONTROLLERDIR ]] ; then
        [[ -s $CONTROLLERDIR/mpt2-status.txt ]] && awk 'BEGIN{RS="(\n|\r\n)"}/BIOS version/{b=$NF}/Firmware version/{f=$NF}END{printf "%s-%s\n",f,b}' $CONTROLLERDIR/mpt2-status.txt
    else
        awk '{if (x!="") {x=x"-"} ; x=x $0}END{print x}' $1/version_{fw,bios}
    fi
}

get_fwrev_i910() {
    if [[ -n $CONTROLLERDIR ]] ; then
        [[ -s $CONTROLLERDIR/fwrev.txt ]] && tr -d '\r\n' <$CONTROLLERDIR/fwrev.txt
    else
        # isdct reports the firmware for each volume although it is just
        # a single image applied to the drive
        # so we just lift the first volume firmware ID
        # (note no CRLF to avoid having to strip it off later)
        Isdct1 $1 | awk '(NF==22){printf "%s",$21;exit}'
    fi
}

get_fwrev_sata() {
    echo "(N/A)"
    return 0
}

get_fwrev_nvme() {
    if [[ -n $CONTROLLERDIR ]] ; then
        [[ -s $CONTROLLERDIR/smartctl_a.txt ]] && awk 'BEGIN{RS="(\n|\r\n)"}/^Firmware Version:/{print $NF;exit}' $CONTROLLERDIR/smartctl_a.txt
    else
        Isdct3 /dev/${1##*/}n1 show -d Firmware | awk '/^Firmware :/{print $NF}'
    fi
}

# helper function to retrieve the current firmware version for the
# nominated controller
# p1=hostN
# p2=controller_type
# p3=pciBus/pciID
get_fwrev() {
    if [[ $(type -t "get_fwrev_$2") = function ]] ; then
        get_fwrev_$2 $1 $3
    else
        return 1
    fi
}

#########################################################################
#
# Retrieve list of current HDDs

# awk script to extract normalised HddId and CurrFw from smartctl -a output
# SAS and SATA print things differently
# line 1 is taken to be the drive id injected separately
awk_smartctl_driveinfo='
BEGIN{
    RS="\r?\n"
    FS="[[:space:]]*:[[:space:]]*"
}
/^+/{next} # skip set-x lines
(d==""){d=$0}
($1=="Device Model"){m=$2}
($1=="Firmware Version"){r=$2}
($1=="Vendor"){m=$2}
($1=="Product"){m=m $2}
($1=="Revision"){r=$2}
/^EXITCODE/{
    printf "%s %s %s\n",d,gensub(/[^-.[:alnum:]]/,"","g",m),gensub(/[^-.[:alnum:]]/,"","g",r)
    d=""
}
'

# drive id format is eEEsSSdPD
# EE=enclosure SS=slot d=PD
get_drives_megaraid() {
    local d=
    {
        if [[ -n $CONTROLLERDIR ]] ; then
            [[ -e $CONTROLLERDIR/pdlist.txt ]] && cat $CONTROLLERDIR/pdlist.txt
        else
            megacli $1 pdlist
        fi
    } | awk 'BEGIN{RS="\r?\n"}/^Enclosure Device ID/{e=$NF}/^Slot Number/{s=$NF}/^Device Id:/{printf "e%ds%dd%d\n",e,s,$NF}'
}

# p1=hostN
# prints "sdX"
# TODO does this work for mixed drives on mpt*sas controllers?
get_drives_scsi() {
    (
    shopt -s nullglob
    if [[ -n $CONTROLLERDIR ]] ; then
        [[ -n "$(echo $CONTROLLERDIR/linuxdev.*.txt)" ]] && awk 'BEGIN{RS="\r?\n"}/^node:/{print gensub(/.*\//,"",1,$0)}' $CONTROLLERDIR/linuxdev.*.txt
    else
        if [[ -n "$(echo $1/device/port*)" ]] ; then
            # use NF-4 to copy with direct and enclosure drives
            find $1/device/port* -name sg\* | awk -F/ 'BEGIN{e=1}{printf "%d\n",gensub(/.*:/,"",1,$(NF-4));e=0}END{exit e}'
        else
            find $1/device/ -name 'target[0-9]*' | xargs -I Z find Z -name 'sd[a-z]' | sed -e 's,.*/,,'
        fi
    fi
    )
}

# p1=hostN
# nvme firmware is handled at the controller level
get_drives_nvme() {
    :
}

# obtain a list of all HDDs in the system
# p1=hostN
# p2=controller type
# prints hddId hddModel currFW
# for scsi_generic it prints the target within the host (N) as this makes sense
#   for mpt*sas where there is more than 1 drive per controller
# if none present, for straight drives it prints sdX
get_drives_live() {
    {
        case $2 in
            mpt2sas) get_drives_scsi $1 ;;
            mptsas)  get_drives_scsi $1 ;;
            i910)    get_drives_scsi $1 ;;
            sata)    get_drives_scsi $1 ;;
            *)
                if [[ $(type -t "get_drives_$2") = function ]] ; then
                    get_drives_$2 $1
                else 
                    return 1
                fi
                ;;
        esac
    } | while read d ; do
        : $1 $2 $d
        echo $d
        SmartctlHost "$1" "$2" "$d" -i
    done
}


# megaraid - just parse pdlist.txt
# sda - look in linuxdev.X to find 
get_drives_offline() {
    {
        # this block will print "drive index" pairs
        if [[ $(type -t "get_drives_$2") = function ]] ; then
            # megaraid already copes with parsing pdlist in offline mode
            # we just have to split the drive index out from the device locator
            # so that we can find the smartctl file
            get_drives_$2 $1 | sed -e 's/\(e[0-9]*s[0-9]*d\([0-9]*\)\)/\1 \2/'
        else 
            # parse linuxdev to find the drive indices
            # "drive" comes from node in linuxdev
            # "index" comes from the filename
            local f
            awk 'BEGIN{RS="\r?\n"}/^index:/{i=$NF}/^node:/{printf "%s %d\n",$NF,i}' $CONTROLLERDIR/linuxdev.*.txt
        fi
    } | while read d i ; do
        : $1 $2 $d $i
        [[ -n $d && -n $i ]] || continue
        echo ${d##*/}
        if [[ -e $CONTROLLERDIR/smartctl_a.$i.txt ]] ; then
            cat $CONTROLLERDIR/smartctl_a.$i.txt
        elif [[ $i == 1 && -e $CONTROLLERDIR/smartctl_a.txt ]] ; then
            cat $CONTROLLERDIR/smartctl_a.txt
        fi
    done
}

get_drives() {
    # can't use SmartctlHost if regenerating logs
    if [[ -n $CONTROLLERDIR ]] ; then
        get_drives_offline "$@"
    else
        get_drives_live "$@"
    fi | awk "$awk_smartctl_driveinfo"
}


# utility to print list of drives in system
print_drives_controller() {
    echo "Host: ${1##*/}"
    get_drives "$@" | sed -e 's,^,  ,'
}
print_all_drives() {
    each_controller print_drives_controller
}

#########################################################################
#
# obtain the PCI device /sys directory for the given hostN
# p1=hostN
get_pci_dir () {
    # convert hostN directory to PCI device directory
    {
        if [[ -n $CONTROLLERDIR ]] ; then
            [[ -s $CONTROLLERDIR/../sys.txt ]] && awk -v c="$1" 'BEGIN{RS="(\n|\r\n)"}($0~c" "){print $NF}' $CONTROLLERDIR/../sys.txt
        else
            readlink -f $1
        fi
    } | sed -e 's,\(.*/[0-9a-fA-F:.]*\)/.*,\1,'
}

# obtain the PCI device:vendor for the given hostN
# p1=hostN
get_pci_device () {
    # convert 0xVVVV 0xDDDD vendor,device into VVVV:DDDD
    if [[ -n $CONTROLLERDIR ]] ; then
        [[ -s $CONTROLLERDIR/../lspci-n.txt ]] && awk -v p=$(get_pci_dir $1) 'BEGIN{RS="(\n|\r\n)";sub(/.*\/0000:/,"",p)}($1==p){printf "%s\n",$3}' $CONTROLLERDIR/../lspci-n.txt
    else
        printf "%04x:%04x\n" $(cat $(get_pci_dir $1)/{vendor,device})
    fi
}

# obtain the PCI device subsystem vendor:id for a given hostN
get_pci_subsystem() {
    # convert 0xVVVV 0xDDDD vendor,device into VVVV:DDDD
    if [[ -z $CONTROLLERDIR ]] ; then
        # on a live system it's easy
        printf "%04x:%04x\n" $(cat $(get_pci_dir $1)/{subsystem_vendor,subsystem_device})
        return
    fi

    # retrospectively running when regenerating summary
    # it's somewhat harder...

    if [[ -e $CONTROLLERDIR/../lspci-vx.txt ]] ; then
        # we have a verbose PCI dump, use that
        # subsystem line might look like:
        # Subsystem: Intel Corporation Device 8086
        # Subsystem: [8086:1234]
        # Subsystem: 8086:1234
        # Subsystem: Intel Corporation devicedescription string
        local a='
            BEGIN{
                RS="(\n|\r\n)"
                sub(/.*\/0000:/,"",p)
            }
            ($0~"^"p" "){want=1;next}
            (want==0)||!/Subsystem:/{ next }
            ($NF~"\[[[:xdigit:]:]*\]") {
                printf "%s\n",gensub(/[^[:xdigit:]:]/,"","g",$NF)
                exit
            }
            ($NF~/^[[:xdigit:]]*:[[:xdigit:]]*$/) {
                printf "%s\n",$NF
                exit
            }
            {
                v="0000"
                d="0000"
                if ($0~/Intel Corporation/) { v="8086" }
                if ($0~/\<LSI\>/) { v="1000" }
                if ($0~/Dell/) { v="1028" }
                if ($NF=="SROMBSASMP2") { d="3505" }
                if ($NF~/^\[[[:xdigit:]]*\]$/) { d=gensub(/[^[:xdigit:]]/,"","g",$NF) }
                if ($NF~/^[[:xdigit:]]*$/) { d=$NF }
                if ((v=="0000")||(d=="0000")) {
                    exit 1
                } else {
                    printf "%s:%s\n",v,d
                    exit
                }
            }
        '
        # only return from here if we identified the device
        awk -v p="$(get_pci_dir $1)" "$a" $CONTROLLERDIR/../lspci-vx.txt && return
    fi

    # we need to dig around a bit more...
    local controller_type=$(printable $CONTROLLERDIR/controller.txt)
    case $controller_type in
        megaraid) # megaraid controllers - look in adpallinfo.txt
            [[ -s $CONTROLLERDIR/adpallinfo.txt ]] && awk 'BEGIN{RS="(\n|\r\n)"}/^SubVendorId/{v=$NF}/^SubDeviceId/{printf "%s:%s\n",v,$NF;exit}' $CONTROLLERDIR/adpallinfo.txt
            ;;
        mptsas)   # SAS106xE - look in sasflash.txt and work backwards
            local sf=$CONTROLLERDIR/sasflash.txt
            local v=
            local s=
            if [[ -e $sf ]] ; then
                if grep -qw Dell $sf ; then
                    v="1028"
                    if grep -qw SAS6IRA $sf ; then
                        s="1f0e"
                    fi
                elif grep -qw Intel $sf ; then
                    v="8086"
                    if grep -qw AXX4SASMOD $sf ; then
                        s="34dc"
                    fi
                fi
            fi
            [[ -n $v && -n $s ]] && echo "$v:$s"
            ;;
        mpt2sas)
            # difficult to detect this
            # likely won't make too much difference since all chips use same firmware
            [[ -s $CONTROLLERDIR/sas2ircu.txt ]] && grep -q SAS2308_2 $CONTROLLERDIR/sas2ircu.txt && echo "8086:3517"
            ;;
        i910)
            # post dates the lspci-vs so should not happen
            echo "8086:3700"
            ;;
        *)  # often SATA
            : unknown controller type $controller_type
    esac
}

# get the /sys entry for /dev/sdY
lookup_sys_from_sd () {
    local l=${1##*/}
    [[ -d /sys/block/$l ]] && { echo /sys/block/$l ; return 0 ; }
    [[ -d /sys/class/scsi_generic/$l ]] && { echo /sys/class/scsi_generic/$l ; return 0 ; }
    return 1
}

# get the /dev/sgX node from /dev/sdY
lookup_sg_from_sd () {
    local sys sg
    sys=$(lookup_sys_from_sd $1) || return
    sg=$(readlink -e $sys/device/generic) || return
    echo ${sg##*/}
}

#########################################################################
#
# check that all drives are optimal
# return 0 if OK, 1 otherwise
# prints list of LDs not in optimal state
# TODO check SMART data

# TODO normalise volume status
a_check_optimal_megaraid='
BEGIN{
    e=0
}
/^Virtual Drive:/{l=$3}
($1=="State")&&((all!="")||($NF!="Optimal")){
    e=1
    printf "LD %s (%s)\n",l,gensub(/^[^:]*: /,"",1,$0)
}
END{exit e}'
# TODO normalise volume status
a_check_optimal_mptsas='
BEGIN{
    e=0
    FS=", "
}
($1~/vol_id/)&&((all!="")||(!/OPTIMAL/)){
    e=1
    split($1,x," ")
    s=gensub(/^[^[:space:]]+[[:space:]]+/,"",1,$4)
    printf "LD %s (%s)\n",x[3],s
}
END{exit e}'

# TODO normalise volume status
a_check_optimal_mpt2sas='
BEGIN{
    e=0
}
/^IR volume [0-9]/{v=$NF}
/Status of volume/&&((all!="")||(!(/OKY/||/OPT/))){
    e=1
    printf "LD %s %s\n",v,gensub(/.*: /,"",1,$0)
}
END{exit e}'

check_optimal_megaraid () {
    megacli $1 ldpdinfo | awk -v all=$3 "$a_check_optimal_megaraid"
}

check_optimal_mptsas () {
    mptstatus $1 | awk -v all=$3 "$a_check_optimal_mptsas"
}

check_optimal_mpt2sas () {
    Sas2ircu $1 display | awk -v all=$3 "$a_check_optimal_mpt2sas"
}

# TODO i910 check for enough volumes present
check_optimal_i910 () {
    return 0
}

# nothing we can check on NVME
check_optimal_nvme () {
    return 0
}

check_optimal_sata () {
    return 0
}

# p1=hostN
# p2=controller type
# p3=pciBus/pciID
# return 0 if OK, 1 otherwise
# prints list of LDs not in optimal state
check_optimal () {
    if [[ $(type -t "check_optimal_$2") = function ]] ; then
        check_optimal_$2 $1 $3
    else
        return 1
    fi
}

# p1=hostN
# p2=controller type
# p3=pciBus/pciID
# prints list of all LDs
print_ld_info () {
    if [[ $(type -t "check_optimal_$2") = function ]] ; then
        check_optimal_$2 $1 $3 all
    else
        return 1
    fi
}

#########################################################################
#
# helper to find out if partitions of $1 are mounted or not

# awk script to see if mounts of /dev/* filesystems are hosted by the
# host adapter passed as variable h
# exits with code 1 if a filesystem is mounted
a_checkmounts='
($1!~/\/dev\//){next}
{
    c="readlink -f /sys/class/block/" gensub(/\/dev\//,"",1,$1)
    c|getline x
    close(c)
    if (x ~ "/"h"/"){exit 1}
}'

check_for_mounts() {
    awk -v h=${1##*/} "$a_checkmounts" /proc/mounts
}

# p1=/sys dir for controller
get_controller_type() {
    # typically megaraid_sas, ata_piix or mptsas, ahci, mpt2sas, isci...
    local cf=
    if [[ -n $CONTROLLERDIR ]] ; then
        cf=$CONTROLLERDIR/controller.txt
    elif [[ $1 = *nvme* ]] ; then
        echo nvme
        return
    else
        cf=$1/proc_name
    fi

    # get a printable string for the controller type and map it
    cf="$(printable $cf)"
    case "$cf" in
        megasr)    echo megaraid ;; # ESRT2
        megaraid*) echo megaraid ;;
        mptsas)    echo mptsas ;;
        mptspi)    echo mptsas ;;
        mpt2sas)   # check for i910
                   local s=$(cat $(readlink -f $1)/../../../subsystem_{vendor,device} )
                   if [[ $s = $'0x8086\n0x3700' ]] ; then
                       echo i910
                   else
                       echo mpt2sas
                   fi
                   ;;
        i910)      echo i910;;
        *)         echo sata ;;
    esac
}

#########################################################################
#
# call given function for each disk controller found
each_controller() {
    local func=$1
    local controller=
    local ct=
    local controller_type=
    local pcidir=
    shift

    if [[ -n $DEBUGDIR ]] ; then
        # in debug mode we just pick up the controller from the directory
        # given and use that
        host=/sys/class/scsi_host/host0
        controller_type=$(dos2unix <$DEBUGDIR/controller.txt) 2>/dev/null || controller_type=megaraid
        controller=1234:5678/1000:0099
        $func $host $controller_type $controller
        return
    fi

    local controllers="$*"
    [[ -n $controllers ]] || controllers=/sys/class/scsi_host/host*

    # identify RAID controllers - print PCI bus / PCI ID
    for host in $controllers ; do

        # convert the hostN into a PCI bus / PCI ID
        pcidir=$(get_pci_dir $host)
        controller=$(printf "%s/%04x:%04x\n" ${pcidir##*/0000:} $(printable $pcidir/vendor) $(printable $pcidir/device) )

        # work out the controller type
        controller_type=$(get_controller_type $host)

        # call the user function
        # $host = /sys/class/scsi_host/hostX
        # $controller_type = megaraid/mpt2sas/mptsas/sata/i910
        # $controller = pcibus/vid:did
        $func $host $controller_type $controller || break

    done

    # NVME devices
    local nvmehosts="$(shopt -s nullglob ; echo /sys/class/nvme/*)"
    for host in $nvmehosts ; do

        # convert the hostN into a PCI bus / PCI ID
        pcidir=$(get_pci_dir $host)
        controller=$(printf "%s/%04x:%04x\n" ${pcidir##*/0000:} $(printable $pcidir/vendor) $(printable $pcidir/device) )

        # work out the controller type
        controller_type=nvme

        # call the user function
        # $host = /sys/class/scsi_host/hostX
        # $controller_type = megaraid/mpt2sas/mptsas/sata/i910
        # $controller = pcibus/vid:did
        $func $host $controller_type $controller || break

    done

}

##################################################################
#
# isdct3 functions
#
# cache the mapping from internal path to isdct3 index
ISDCT3MAP=$TMPDIR/isdct3map.txt
rm -f $ISDCT3MAP

# where to find isdct3 binary
isdct3=$__mydir/../bin64/isdct3/isdct

# look up an internal path to isdct3 index
# mapping file is DevicePath SerialNumber Index
# TODO how else does isdct3 report DevicePath
isdct3_index () {
    local a='
        function printit() {
            if (i != "") { printf "%s %s %s\n",dp,sn,i }
            dp=""
            sn=""
            i=""
        }
        /^[[:space:]]*$/{next}
        /^- /{ printit() }
        /^DevicePath : /{dp=$NF}
        /^Index : /{i=$NF}
        /^SerialNumber : /{sn=$NF}
        END{ printit() }
    '

    # create a cache of the known drives, if not already done
    if [[ ! -e $ISDCT3MAP ]] ; then
        $isdct3 show -intelssd | awk "$a" >$ISDCT3MAP
    fi

    awk -v id="$1" 'BEGIN{e=1}($1==id)||($2==id)||($3==id){print $3;e=0;exit}END{exit e}' $ISDCT3MAP
}

# wrapper around isdct3
# auto adds -intelssd N
# p1 = disk identifier e.g. drive number or serial or node
# p* = isdct3 arguments
Isdct3 () {
    local i
    i=$(isdct3_index "$1") || return
    shift
    local cmd=$1
    shift
    if [[ $1 == "-a" || $1 == "-all" ]] ; then
        # -a has to come before the -intelssd
        cmd="$cmd -a"
        shift
    fi
    if [[ $1 == "-d" || $1 == "-display" ]] ; then
        # so does -d xxx
        cmd="$cmd $1 $2"
        shift 2
    fi
    $isdct3 $cmd -intelssd $i "$@"
}
