#!/bin/sh


VERSION=1552662819

if [ "$(uname -r)" = "5.10" ] ; then
    echo "Solaris 10 not supported at this time."
    exit 99
fi

now=$(date +%s)

tmpdir=/tmp/coraid-$(hostname)-${now}
outfile=/tmp/coraid-$(hostname)-${now}.txt

if [ -t 1 -a -t 0 ] ; then # running in a terminal?
    MODE=file
    GRABMSGS=0
    EXTENDED=1 #extended is now the default. -E turns it off.
    HEADERS=1
    while getopts Eehlmtvx: flag
    do
        case $flag in
            E)
                EXTENDED=0
                ;;
            e)
                EXTENDED=1
                echo "Please be patient. Extended diagnostics may take several minutes to collect."
                ;;
            h)
                echo Usage:
                printf "%s [-h] | [-e] [-m] [-t]\n" "${0}"
                printf "\t-h : Show this help and exit\n"
                printf "\t-E : Disable extended diagnostics\n"
                printf "\t-e : Deprecated. left for backwards compatibility\n"
                printf "\t-m : Capture a copy of OS's messages file\n"
                printf "\t-t : Capture diagnostics in tarball format\n"
                exit 0
                ;;
            l)
                MODE=local
                ;;
            m)
                GRABMSGS=1
                ;;
            t)
                MODE=tar
                ;;
            v)
                echo Version: ${VERSION}
                exit 0
                ;;
            x)
                EXEX="${OPTARG}"
                HEADERS=0
                ;;
        esac
    done
else # running in a pipeline?
    [ -z "${MODE}" ] && MODE=file
    [ -z "${GRABMSGS}" ] && GRABMSGS=0
    [ -z "${EXTENDED}" ] && EXTENDED=1 #extended is now the default. -E turns it off.
    [ -z "${HEADERS}" ] && HEADERS=1
fi
if [ "${MODE}" = tar ] ; then
    mkdir -p ${tmpdir}
    cd ${tmpdir}
elif [ -z "${EXEX}" -a "${MODE}" = file ] ; then
    exec >${outfile}
fi

merooty(){
    if [ "$(id -u)" != 0 ]; then
        echo "please run as root" >&2
        exit 1
    fi
}

cleanup(){
    cd /tmp
    [ "${MODE}" = "tar" ] && rm -rf ${tmpdir}
}
trap "cleanup" EXIT
sepuku(){
    cleanup
    exit
}
trap "sepuku" INT

have(){
    unset -v have;
    type "${1}" > /dev/null 2>&1 && have='yes'
}

header(){
    if [ ${HEADERS} = 1 ] ; then
        printf "\n==========================================\n"
        echo "${@}"
        printf "==========================================\n"
    fi
}

unslash(){
    echo "${*}" | sed -e 's/\//_/g' -e 's/[^A-Za-z0-9._-]/-/g'
}

run(){
    run="${1}"
    shift
    label="${@}"
    if [ -z "${label}" ] ; then
        label=$run
    fi
    if [ -z "${EXEX}" ] ; then
        printf . >&2
    fi
    if [ "${MODE}" = "tar" ] ; then
        label=$(unslash $label)
        eval ${run} >> ${label} 2>&1
    else
        header "${label}"
        eval ${run} 2>&1
    fi
}

grab(){
    if [ "${MODE}" = "tar" ] ; then
        grep -h . "${1}" >> $(basename ${1})
    else
        header "${1}"
        grep -h . "${1}"
    fi
}

columnt(){
    awk '{ lines[x++] = $0; for (i=1; i<=x; i++){ split($0,line); for (j=1; j<=NF; j++){ if ( length(line[j]) > widths[j] ){ widths[j] = length(line[j]); } } } }END{ for (k=0; k<=x; k++){ z = split(lines[k],myline); for (w=1;w<=z;++w){ printf("%-"widths[w]"s ",myline[w]); if( w == z ) print ""; } } }'
}

if have column ; then
    unset -f columnt
    alias columnt='column -t'
fi

driver(){
    if [ "${MODE}" = "tar" ] ; then
        mkdir driver
        cd driver
    fi
    DRVLOC=uninstalled
    if [ -e /proc/scsi/ethdrv ] ; then
        DRVLOC="/proc/scsi/ethdrv/ethdrv."
        loopdriver ${DRVLOC}
    fi
    if [ -e /proc/ethdrv ] ; then
        DRVLOC=/proc/ethdrv/
        loopdriver ${DRVLOC}
        case ${me} in
            Linux)
                run ethdrv-stat
                ;;
        esac
    fi
    if [ "${me}" = SunOS -a -e /dev/ethdrv ] ; then
        DRVLOC=/dev/ethdrv/
        if pkginfo | grep CORDethdrv >/dev/null 2>&1 ; then
            loopdriver ${DRVLOC}
        else
            run 'echo "HBA Driver either too old or not installed."' 'nodriver'
        fi
        have ethdrvadm && run "ethdrvadm list-devices"
    fi
    if [ -e /proc/ethdrv.release ] ; then
        DRVLOC="/proc/ethdrv."
        loopdriver ${DRVLOC}
    fi
    if [ ! -e ${DRVLOC} -o "${DRVLOC}" = "uninstalled" ] ; then
        run 'echo "HBA Driver either too old or not installed."' 'nodriver'
    fi
    [ "${MODE}" = "tar" ] && cd ${tmpdir}
}

loopdriver(){
    if [ -z "${EXEX}" ] ; then
        printf . >&2
    fi
    DRVLOC=${1}
    for f in ${DRVLOC}* ; do
        if [ "${f}" = "${DRVLOC}cec" ] ; then continue ; fi
        if [ "${f}" = "${DRVLOC}ns" ] ; then continue ; fi
        case "${f}" in
            *config|*corestats|*elstats|*ifstats)
                grab "${f}"
                ;;
            *)
                DHEADERS=''
                if [ "${f}" = "${DRVLOC}acbs" ] ; then
                    DHEADERS='ln 4 s.s cwrk mxwn cscsi caoe cmds rtx unre'
                fi
                if [ "${f}" = "${DRVLOC}ca" ] ; then
                    DHEADERS='ln s.s cwrk clamp mxwn ssthresh rttavg rttdev'
                fi
                if [ "${MODE}" = tar ] ; then
                    cat "${f}" > "$(basename ${f})" #original
                    DDEST="$(basename ${f})-t"    #column-t'ed
                    if [ ! -z "${DHEADERS}" ] ; then
                        (echo "${DHEADERS}" ; cat "${f}") | columnt >> "${DDEST}"
                    else
                        grep -h . "${f}" | columnt >> "${DDEST}"
                    fi
                else
                    header "${f}"
                    if [ ! -z "${DHEADERS}" ] ; then
                        (echo "${DHEADERS}" ; cat "${f}") | columnt
                    else
                        grep -h . "${f}" | columnt
                    fi
                fi
                ;;
        esac
    done
}

targeted(){
    if [ "${me}" = "SunOS" ]; then
        if [ "${MODE}" = local ] ; then
            # :(
            DRVLOC=/dev/ethdrv/
        fi
        targets=$(for zpool in $(zpool list -H -o name |egrep -v 'rpool|syspool') ; do zpool status "${zpool}" |awk '{print $1}' |egrep '^c[0-9]+t' |sort -n |uniq |sed -e 's/^c[0-9]*t//' -e 's/d/\./'; done)
    fi
    if [ "${me}" = "VMkernel" ]; then
        if [ "${MODE}" = local ] ; then
            DRVLOC=/proc/ethdrv/
        fi
        targets=$(mapnaatoctd | awk '{print $2}')
    fi
    if [ -n "${targets}" ] ; then
        if [ "${MODE}" = local ] ; then
            diagconcatenator ${targets} | columnt
        else
            run "diagconcatenator ${targets} | columnt" targeted-diags
        fi
    fi
}

diagconcatenator(){
    if [ ! -e "${DRVLOC}acbs" ] ; then
        return ""
    fi
    grep=grep
    if [ "${me}" = "SunOS" ]; then
        grep=/usr/xpg4/bin/grep
    fi
    echo 's.s 4 cwrk mxwn clamp cscsi caoe cmds rtx unre ssthresh rttavg rttdelt'
    for t in ${@} ; do
        $grep -hE "^[[:digit:]]+ 4*[[:space:]]*$t " "${DRVLOC}acbs" "${DRVLOC}ca" | sed -e 'H;$!d;x;s/\n/ /g' -e 's/^ //' | awk '{print $3 " " $2 " " $4 " " $5 " " $14 " " $6 " " $7 " " $8 " " $9 " " $10 " " $16 " " $17 " " $18}'
    done
}


#esx
esxversion(){
    run "vmware -v"
    run "esxcli system maintenanceMode get"
}

esxmpath(){
    run "esxcfg-mpath -L"
}

esxmodinfo(){
    run "esxcfg-module -i ethdrv"
}

esxvolume(){
    run "esxcfg-volume -l"
}

esxscsidevs(){
    run "esxcfg-scsidevs -m"
}

esxnas(){
    run "esxcfg-nas -l"
}

esxnics(){
    run "esxcfg-nics -l"
}

esxvswitch(){
    run "esxcfg-vswitch -l"
}

esxvmknic(){
    run "esxcfg-vmknic -l"
}

lsvms(){
    run 'vim-cmd vmsvc/getallvms'
}

esxsnapshotsandvmdkinfo(){
    local table=$(vim-cmd vmsvc/getallvms | grep -v Vmid | grep '^[0-9]' | sed -e 's/\[.*//' | awk 'ORS=":"')
    # determine what VMs are powered on
    out=""
    count=0
    OLDIFS=$IFS
    IFS=':'
    for h in $table ; do
        vmnum=$(echo "${h}" | awk '{print $1}')
        vmlabel=$(echo "${h}" | sed -e 's/^ *//g' -e 's/ *$//g' -e 's/^[0-9]* *//')
        run "vim-cmd vmsvc/get.filelayout ${vmnum} 2>/dev/null | grep -C2 -E 'vmdk|vmsn'" "get.filelayout ${vmlabel}"
        run "vim-cmd vmsvc/snapshot.get ${vmnum}" "snapshot.get ${vmlabel}"
        if vim-cmd vmsvc/power.getstate "${vmnum}" | grep 'Powered on' >/dev/null 2>&1; then
            out="${out}${vmlabel} "
            count=$(expr $count + 1)
        fi
    done
    if [ -n "${out}" ] ; then
        run "echo '$out'" "Powered on VMs ${count}"
    fi
    IFS=$OLDIFS #probably unnecessary
}

esxhwproduct(){
    if have esxcfg-info ; then
        run "esxcfg-info | head | grep 'Product Name' | awk -F. '{print \$NF}'" "Hardware Product Info"
    fi
}

esxHV(){
    if have esxcfg-info ; then
        # http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1011712
        run 'esxcfg-info |grep "HV Support"' "Hardware Virtualization Support"
    fi
}

mapnaatoctd(){
    esxcfg-mpath -L | sort | awk '{print $1 " " $3}' |  awk "BEGIN { n=1; while (getline < \"${DRVLOC}devices\" > 0){ target[\$1] = n; aoe[n] = \$2; n++; } while (\"esxcfg-scsidevs -m\" | getline) { naa = \$1; naal[naa] = \$5; for( i=6; i<=NF; i++){ naal[\$1] = naal[naa] \" \" \$i; } } }{ if (target[\$1]){ mtarget=\$1; mnaa=\$2; print mtarget \" \" aoe[target[mtarget]]\" \" mnaa \" \" naal[mnaa\":1\"] }else{ ignore } }" | sort -k2
}

wrapmap(){
    run mapnaatoctd "naa-map"
}

esxlspci(){
    run "lspci -v"
    run "lspci -p"
}

esxstoragerules(){
    run "esxcli storage nmp satp rule list"
    run "esxcli storage nmp device list"
    run "esxcli storage core device vaai status get"
    run "esxcli storage core device list"
}

esxdmesg() {
    run "tail -100 /var/log/vmkernel.log"
}
#end ESX

#solaris

ethercloud(){
    if [ ! -e "/opt/coraid/ethercloud" ] ; then
        return
    fi
    run "/opt/coraid/ethercloud/exec/all_lun_info" "All LUN info"
    run "ls -ltR /opt/coraid/ethercloud" "ethercloud contents"
    if [ -e "/etc/puppet/hiera" ] ; then
        for f in /etc/puppet/hiera/* ; do
            grab ${f}
        done
    fi
    for f in /opt/coraid/ethercloud/events/* ; do
        grab ${f}
    done
    # some of the files here are .gz so only grab *.log
    for f in /opt/coraid/ethercloud/logs/*.log ; do
        grab ${f}
    done
    if [ "${MODE}" = "tar" ] ; then
        for f in /opt/coraid/ethercloud/logs/*.gz ; do
            grab ${f}
        done
    fi
}

solgrub(){
    if have bootadm ; then
        if [ ${solflavor} = nexenta ] ; then
            :
        else
            run "bootadm list-menu" grub-menu
            if [ ${solflavor} = "111plus" ] ; then
                run "bootadm list-menu -i $(bootadm list-menu |grep default |awk '{print $2}')" grub-default-details
            fi
        fi
    fi
}

soleeprom(){
    if [ ${solflavor} = nexenta ] ; then
        :
    else
        have eeprom && run "eeprom" eeprom
    fi
}

solsmarthost(){
    if grep ^DS /etc/mail/sendmail.cf >/dev/null 2>&1 ; then
        run 'grep ^DS /etc/mail/sendmail.cf |sed "s/^DS//"' sendmail-smarthost
    fi
}

ethdrvadmlistdevicesa(){
    have ethdrvadm && run "ethdrvadm list-devices -a"
}

solEClogs(){
    if [ -d /opt/coraid/ethercloud ] ; then
        run "du -sh /opt/coraid/ethercloud/logs* 2>/dev/null" du-sh_EtherCloud_logs
    fi
}

solexplorer(){
    have explorer && run "explorer -version |grep ^Explorer" explorer
}

solarismapnaa(){
    awk 'BEGIN{ i=0; x=0; y=0; sds="";OFS=" "; while ( getline < "/dev/ethdrv/devices" > 0){ aoe[$1] = $2; } while ("iostat -x" | getline ){ if ( /^sd/ ){ sda[i] = $1; sds = sds " " $1; i++; } else { ignore; } } close("iostat -x"); while ("iostat -Ein " sds | getline ){ if ( /^(c|sd)/ ){ ctda[x] = $1; x++; } else if ( /^Vendor/ ){ if ($NF ~ /^id1,/){ sub(/id1.sd./,"",$NF); naaa[y] =  $NF; }else{ naaa[y] = ""; } y++; } else { ignore; } } close("iostat -x" stds); for(n = 0; n < y; n++){ print ctda[n], sda[n], naaa[n], aoe[sda[n]]; } }' | columnt
}
oldsolarismapnaa(){
    # find the ctds
    for ctd in $(iostat -xn | ggrep -E 'c[[:digit:]]+t[[:digit:]]' | awk '{print $NF}') ; do
        # some devices might not be in use, so only print out naa records
        naa=$(prtconf -v "/dev/rdsk/${ctd}" 2>/dev/null| ggrep ',sd@' | cut -d@ -f 2 | sed -e "s/'//g" -e "s/^n//")
        # for our purposes we only care about in-use devices, so only echo them
        if [ -n "${naa}" ] ; then
            # find the sd device by unfortunately calling iostat many many times
            sd=$(iostat -x "${ctd}" | grep sd | cut -f 1 -d ' ')
            echo "${sd} ${naa} ${ctd}"
        fi
    # now look up these devices in our driver file
    done | gawk "
    BEGIN {
        n=1;
        while (getline < \"/dev/ethdrv/devices\" > 0){
            target[\$1] = n;
            aoe[n] = \$2;
            n++;
        }
    }{
        if (target[\$1]){
            sd=\$1;
            mnaa=\$2;
            ctd=\$3;
            print sd \" \" mnaa \" \" ctd \" \" aoe[target[sd]] 
        }else{
            ignore
        }

    }" | columnt
}
wrapsolarismapnaa(){
    run solarismapnaa naa-map
}

solethdrvstats(){
    kstat -p -c kmem_cache |grep ethdrv |awk -F":" '{print $3":"$4"\t"$5}' |sort -n |columnt
}

solcstates(){
    if [ $(kstat -p cpu_info:::supported_max_cstates |awk '$2 ~ /^[3-9]$/' |wc -l) -gt 0 ] ; then
        run 'echo "CPU C-States detected - please disable in BIOS"' CPU_C-STATES-detection
    fi
}

solbe(){
    have beadm && run "beadm list" beadm-list
}

soldumps(){
    run dumpadm dumpadm
    run 'ls -ltrhF /var/crash/* 2>/dev/null' crashdumps
}

solcores(){
    run coreadm coreadm
    run 'ls -ltrhF /var/cores/* 2>/dev/null' coredumps
}

solupdates(){
    gawk 'function fmri(str) { sub(/p.*,/,"",str); sub(/^5./,"",str); sub(/:.*/,"",str); sub(/-0.175/,"",str); return str; } function dateme(str) { sub(/Z-...xml/,"",str); sub(/.*\//,"",str); year  = substr(str,1,4); month = substr(str,5,2); day   = substr(str,7,2); hour  = substr(str,10,2); minute= substr(str,12,2); second= substr(str,14,2); str = year " " month " " day " " hour ":" minute ":" second; return str; } { if (/solaris.entire/){ if (/->/){ f = FILENAME; s = fmri($1); e = fmri($3); f = dateme(f); a[f " " s " " $2 " " e] = 1; } } }END{ n = asorti(a,copy); for(i=1;i<=n;i++){ print copy[i]; } }' /var/pkg/history/*
}

solflavors(){
    kernel=$(uname -v)
        if [ ${kernel} = "11.0" ] ; then
            export solflavor=110
        elif ( echo ${kernel} |egrep '11\.[1-9]+' >/dev/null 2>&1 ) ; then
            export solflavor=111plus
        elif ( echo ${kernel} |grep -i nexenta >/dev/null 2>&1 ) ; then
            export solflavor=nexenta
        else
            export solflavor=${kernel}
        fi
}

whatsol(){
    run 'uname -a'
    [ -e /etc/release ] && run 'cat /etc/release' release
    if [ -s /opt/coraid/release ] ; then
        grab /opt/coraid/release
    fi
    iam=$(smbios -t SMB_TYPE_SYSTEM | tr "\n" ';')
    man=$(printf "%s" "${iam}" | tr ';' "\n" | grep Manufacturer: | awk -F: '{print $NF}' |sed 's/^[ \t]*//')
    prod=$(printf "%s" "${iam}" | tr ';' "\n" | grep Product: | awk -F: '{print $NF}' |sed 's/^[ \t]*//')
    ver=$(printf "%s" "${iam}" | tr ';' "\n" | grep Version: | awk -F: '{print $NF}' |sed 's/^[ \t]*//')
    run "echo ${man}" manufacturer
    run "echo ${prod}" product
    run "echo ${ver}" version
    if echo "${man}" |grep -i coraid >/dev/null 2>&1 ; then
        run "sg_vpd --page=sn /dev/es/ses0 |grep \"Unit serial number\" |grep -v VPD |awk '{print \$NF}'" sneep
    else
        serial=$(printf "%s" "${iam}" | tr ';' "\n" | grep "Serial Number:" | awk -F: '{print $NF}' |sed 's/^[ \t]*//')
        run "echo ${serial}" sneep
        #have sneep && run sneep serial
    fi
    have hostid && run hostid
    if [ -s /etc/hostid ] ; then
        grab /etc/hostid
    else
        run "echo WARNING: /etc/hostid missing or empty!" hostid
    fi
    if have pkg ; then
        run 'pkg info entire'
        run "solupdates |columnt" update-history
        run "pkg publisher solaris" pkg-publisher
        run "pkg info idr\* 2>/dev/null" pkg-info-idr
    fi
    solgrub
    solbe
    soleeprom

}

solilom(){
    if have ilomconfig ; then
        if diskinfo -v |grep "SUN-FIRE" >/dev/null 2>&1 ; then
            for value in system-summary user identification network dns clock interconnect ; do
                run "ilomconfig list ${value}" ilomconfig-${value}
            done
        fi
    fi
}

cscanpci(){
    have scanpci && run 'scanpci -v' scanpci
}

solretired(){
    if [ -f /etc/devices/retire_store ] ; then
        run 'echo "WARNING: /etc/devices/retire_store exists!"' retired-devices
    fi
}

fmtopo(){
    if [ -x /usr/lib/fm/fmd/fmtopo ] ; then
        run '/usr/lib/fm/fmd/fmtopo -Vp' fmtopo-Vp
    fi
}

lsiscan(){
    if have sas2flash ; then
        for c in $(sas2flash -listall 2>/dev/null |egrep ^[0-9] |awk '{print $1}') ; do
            run "sas2flash -c ${c} -list" "LSI firmware c ${c}"
        done
    else
        run "echo sas2flash not found" "sas2flash-not-found"
    fi
}

lsidisks(){
    if have sas2ircu ; then
        for c in $(sas2ircu LIST 2>/dev/null |awk '{print $1}' |egrep ^[0-9]) ; do
            run "sas2ircu ${c} DISPLAY" "sas2ircu ${c} DISPLAY"
        done
    else
        run "echo sas2ircu not found" "sas2ircu-not-found"
    fi
}

solipmitool(){
    if diskinfo -v |grep "SUN-FIRE" >/dev/null 2>&1 ; then
        have ipmitool && run "ipmitool fru"
    fi
}

solfw(){
    if diskinfo -v |grep "SUN-FIRE" >/dev/null 2>&1 ; then
        have fwupdate && run "fwupdate list all"
    fi
}

solintrstat(){
    have intrstat && run "intrstat 3 1" intrstat
}

soltuning(){
    for tunable in /etc/system /lib/svc/method/coraid-tuning.sh ; do
        if [ -f "${tunable}" ] ; then
            run 'egrep -v "^#|^\*|LD_LIBRARY_PATH|include.sh|^$" ${tunable}' "${tunable}"
        fi
    done
}

cvmstat(){
    if have vmstat ; then
        run vmstat
        run 'vmstat -s'
    fi
}

fmstatus(){
    have fmstat && run 'fmstat'
}

fmadmconfig(){
    have fmadm && run 'fmadm config'
}

cprtdiag(){
    have prtdiag && run 'prtdiag -v'
}

cfmdump(){
    if have fmdump ; then
        run 'fmdump -t 7d' fmdump
        for uuid in $(fmdump -t 7d |egrep -v '^TIME|Repaired|Resolved' |awk '{print $4}') ; do
            run "fmdump -mv -u ${uuid}" "fmdump-m ${uuid}"
            #run "fmdump -eV -u ${uuid}" "fmdump-eV ${uuid}"
        done
    fi
    #if [ ${GRABMSGS} -eq 1 ] ; then
    #    run "fmdump -eV -t 7d" fmdump-eV-t7d
    #fi
}

cfmfaulty(){
    have fmadm && run 'fmadm faulty -v'
}

csig(){
    have machinesig && run machinesig
}

csvcs(){
    have svcs && run 'svcs -xv'
}

zpoollist(){
    run 'zpool list'
}

#zfslistsnapshots(){
#    run 'zfs list -H -r -t snapshot |egrep -v "rpool|syspool" |columnt' zfs-list-snapshots
#    run 'zfs list -H -r -t snapshot -o snapshot:type,name ||egrep -v "rpool|syspool" }columnt' zfs-list-snapshots-type
#}

solshare(){
    if have sharemgr ; then
        run 'sharemgr show -pv'
    else
        #if [ ${solflavor} = "111plus" ] ; then
        #    run "zfs get -H share.all |columnt" zfs-get-share-all
        #fi
        if have share ; then
            run 'share -A |columnt' share-A
            for s in $(share -A |awk '{print $2}' |sed 's|^/||' |sort) ; do
                if [ ${solflavor} = "111plus" ] || [ ${solflavor} = "110" ] ; then
                    run "zfs get share ${s}" "zfs get share ${s}"
                fi
                if [ ${solflavor} = "111plus" ] ; then
                    run "zfs get share.nfs.all ${s} 2>/dev/null" "zfs get share nfs all ${s}"
                    run "zfs get share.smb.all ${s} 2>/dev/null" "zfs get share smb all ${s}"
                fi
            done
        fi
        if have sharectl ; then
            run 'sharectl get nfs |sort' sharectl-nfs
            run 'sharectl get smb |sort' sharectl-smb
        fi
    fi
}

solcifsmode(){
    have smbadm && run 'smbadm list'
}

solsmbusers(){
    if [ -f /var/smb/smbpasswd ] ; then
        grab /var/smb/smbpasswd
    fi
}

solsidmap(){
    have svccfg && run 'svccfg -s idmap listprop config/unresolvable_sid_mapping' idmap-sid-mapping
}

solsidmapdump(){
    if svcs idmap |grep online > /dev/null 2>&1 ; then
        run 'idmap dump -n' idmap-dump-n
    fi
}

zpoolgetall(){
    for zpool in $(zpool list -H -o name) ; do
        run "zpool status -D ${zpool}"
        run "zpool get all ${zpool}" "zpool get all ${zpool}"
        run "/usr/bin/df -t ${zpool}" df-t-${zpool}
        #run "iostat -xen $(zpool status ${zpool} |awk '{print $1}' |egrep '^c[0-9]+t') 3 1" iostat-${zpool}
        #if [ "${zpool}" != "rpool" ] ; then
            run "zfs list -r -t filesystem,volume ${zpool} |columnt" "zfs list ${zpool}"
            for z in $(zfs list -Hr -t filesystem,volume -o name |egrep -v rpool/'[ROOT|VARSHARE]' |grep ^${zpool} | sort) ; do
                run "zfs list -o space ${z} |columnt" "zfs list space ${z}"
                run "zfs list -r -t snapshot ${z} |columnt" "zfs list snapshots ${z}"
                run "zfs list -r -t snapshot -o snapshot:type,name ${z} |columnt" "zfs list snapshots type ${z}"
                run "zfs get all ${z}" "zfs get all ${z}"
            done
        #fi
        run 'zpool history -l ${zpool} |egrep -v "zfs snapshot|zfs send|zfs recv|zfs destroy|zfs rename"' "zpool trimmed history ${zpool}"
    done
}

solmapdevices(){
    python -c 'import os;devs=[y.split()[0] for y in open("/dev/ethdrv/devices").readlines()];x=[y.split()[0] for y in os.popen("iostat -x").readlines()];xn=[y.split()[-1] for y in os.popen("iostat -xn")];c=dict(zip(x,xn)); print "\n".join(["%s = %s" % (y,c.get(y)) for y in devs])'
}

solcpuinfo(){
    have psrinfo && run 'psrinfo -pv'
}

solcron(){
    if [ -d /var/spool/cron/crontabs ] ; then
        for c in $(find /var/spool/cron/crontabs -type f |grep -v "\.au") ; do
            run "egrep -v '^\#|^$' ${c}" ${c}
        done
    fi
}

solcfgsas(){
    sasinfo hba-port |grep "HBA Port Name" |awk -F"/" '{print $4}'|xargs -i cfgadm -alv {} |egrep -v "Ap_Id|^When"
}

solsasinfo(){
    run "sasinfo hba -v"
    run "sasinfo hba-port -vly"
    run "sasinfo expander -v"
    run "sasinfo lu -v"
    if have sasinfo ; then
        if have sg_logs ; then
            for sas in $(sasinfo lu |grep "/rdsk/" |awk '{print $NF}') ; do
                run "sg_reassign -g ${sas} ; sg_logs --page=0x18 ${sas}" "sg_logs-${sas}"
            done
        fi
    fi
}

soldiskinfo(){
    have diskinfo && run "diskinfo -t disk -o Rcmenf1 -v" diskinfo
    have sasinfo && solsasinfo
    if have mpathadm ; then
        run "mpathadm list lu"
        run "mpathadm list lu |grep '/rdsk/' |xargs -i mpathadm show lu {}" mapthadm-show-lu
    fi
    #if have sdmcmd ; then
    #    for s in $(sdmcmd scanlocal |grep 'devices\[' |awk '{print $NF}' |grep -v other:) ; do
    #        run "sdmcmd getinfo target=${s}" "sdmcmd-getinfo-${s}"
    #    done
    #else
    #    run "echo sdmcmd not found" "sdmcmd-not-found"
    #fi
    for conf in /kernel/drv/scsi_vhci.conf /etc/driver/drv/scsi_vhci.conf /kernel/drv/sd.conf /etc/driver/drv/sd.conf ; do
        [ -f ${conf} ] && run "egrep -v '^\#|^$' ${conf}" ${conf}
    done
    #have stmsboot && run "stmsboot -L"
    #run 'echo "::mptsas -t" | mdb -k' mptsas-t-mdb
}

soldnlc(){
    run 'kstat -n dnlcstats' kstat-dnlcstats
    run 'kstat -n ncstats' kstat-ncstats
}

solswap(){
    if have swap ; then
        run 'swap -lh |columnt' swap-lh
        run 'swap -sh' swap-sh
    fi
    have swapinfo.pl && run "swapinfo.pl" swapinfo.pl
}

solmemstat(){
    run 'echo "::memstat" |mdb -k 2> /dev/null' mdb-memstat
}
zfs_file_data(){
    run "echo ::vmem |mdb -k |egrep '^ADDR|zfs' |awk '{print \$2\" \"\$3\" \"\$4\" \"\$5\" \"\$6}' |columnt" mdb-vmem-zfs_file_data
}

solkmastat(){
    run 'echo "::kmastat -g" | mdb -k 2> /dev/null' mdb-kmastat
}

solirq(){
    run 'echo "::interrupts -d" |mdb -k 2> /dev/null' mdb-interrupts
}

solarcstat(){
    run 'echo "::arc" |mdb -k 2> /dev/null' mdb-arcstat
}

kstatanalyze(){
    # Python 2.6 needs argparse
    # see Solaris 11.1 (ZX) Installation guide
    if pip list |grep argparse >/dev/null 2>&1 ; then
        if have kstat-analyzer.py ; then
            run kstat-analyzer.py kstat-analyzer
        elif have kstat-analyzer ; then
            run kstat-analyzer kstat-analyzer
        fi
    fi
}

solsar(){
    if svcs sar |grep online > /dev/null 2>&1 ; then
        run 'sar -A' sar-A
    fi
}

solipf(){
    have svccfg && run "svccfg -s ipfilter:default listprop firewall_config_default/policy" ipf-default_policy
    if svcs ipfilter |grep online > /dev/null 2>&1 ; then
        run 'ipfstat -hion' ipfstat-hion
        run 'ipnat -l' ipnat-l
        have svccfg && run 'svccfg -s ipfilter:default listprop |grep file' ipf-rule_files
    fi
}

solyp(){
    if svcs network/nis/client |grep online > /dev/null 2>&1 ; then
        run ypwhich
    fi
}

solkernparams(){
    solparamerator << EOP
active_ptables
aok
apic_intr_policy
apic_panic_on_nmi
autoup
availrmem
availrmem_initial
avefree
avefree30
bufhwm
clnt_max_conns
cotsmaxdupreqs
ddi_msix_alloc_limit
desfree
dnlc_max_nentries
dnlc_nentries
dohwcksum
do_tcp_fusion
fastscan
freemem
hardswap
hires_hz
hires_tick
idle_cpu_no_deep_c
idle_cpu_prefer_mwait
ip_squeue_bind
ip_squeue_fanout
ip_squeue_worker_wait
kmem_flags
lotsfree
mac_cpu_binding_on
mac_cpu_socket_binding
maxdupreqs
maxpgio
maxphys
maxusers
minfree
mpss_coalesce_disable
mptsas_enable_msi
ncsize
nfs3_bsize
nfs3_max_threads
nfs3_max_transfer_size
nfs3_max_transfer_size_clts
nfs3_max_transfer_size_cots
nfs3_nra
nfs4_bsize
nfs4_max_threads
nfs4_max_transfer_size
nfs4_max_transfer_size_clts
nfs4_max_transfer_size_cots
nfs4_nra
nfs_bsize
nfs_loaned_buffers
nfs_max_threads
nfs_max_transfer_size
nfs_max_transfer_size_clts
nfs_max_transfer_size_cots
nfs_nra
npages
nscan
obp_pages
pages_locked
pages_pp_maximum
pg_contig_disable
physinstalled
physmem
sd_io_time
sd_max_throttle
sd_xbuf_active_limit
segkmem_lpg_disable
segkmem_lpg_disable_1g
segkmem_lpsize
segkmem_noreloc
segkmem_zio_relocatable
segkmem_zlpsize
softswap
snoop_interval
snooping
sq_max_size
ssd_max_throttle
ssd_xbuf_active_limit
sw_pending_size
swapfs_minfree
swapfs_reserve
tcp_squeue_wput
throttlefree
total_pages
tune_t_fsflushr
ufs_HW
ufs_LW
vpm_enable
EOP
}

solzfsparams(){
    (echo "::zfs_params" |mdb -k 2>/dev/null |awk '{print $1}' |tr '\n' ' ' ; cat <<EOP
arc_grow_retry
arc_loaned_bytes
arc_lotsfree_percent
arc_p_min_shift
arc_reduce_dnlc_percent
arc_shrink_shift
arc_warm
fzap_default_block_shift
l2arc_feed_again
l2arc_feed_min_ms
l2arc_headroom
l2arc_noprefetch
l2arc_norw
l2arc_write_boost
l2arc_write_max
metaslab_aliquot
metaslab_debug
metaslab_df_alloc_threshold
metaslab_df_free_pct
metaslab_gang_bang
metaslab_gang_threshold
metaslab_min_alloc_size
spa_asize_inflation
spa_max_replication_override
spa_mode_global
vdev_mirror_shift
zfetch_array_rd_sz
zfetch_block_cap
zfetch_max_streams
zfetch_min_sec_reap
zfs_arc_max
zfs_arc_meta_limit
zfs_arc_min
zfs_default_bs
zfs_default_ibs
zfs_delay_max_ns
zfs_delay_min_dirty_percent
zfs_delay_scale
zfs_dirty_data_max
zfs_dirty_data_sync
zfs_flags
zfs_free_min_synctime_pct
zfs_immediate_write_sz
zfs_mdcomp_disable
zfs_no_scrub_io
zfs_no_scrub_prefetch
zfs_no_write_throttle
zfs_nocacheflush
zfs_prefetch_disable
zfs_read_chunk_size
zfs_recover
zfs_resilver_delay
zfs_resilver_min_time_ms
zfs_resilver_synctime_pct
zfs_scan_idle
zfs_scan_min_synctime_pct
zfs_scrub_delay
zfs_scrub_limit
zfs_top_maxinflight
zfs_txg_synctime_ms
zfs_txg_timeout
zfs_unmap_ignore_size
zfs_vdev_aggregation_limit
zfs_vdev_async_read_max_active
zfs_vdev_async_read_min_active
zfs_vdev_async_write_active_max_dirty_percent
zfs_vdev_async_write_active_min_dirty_percent
zfs_vdev_async_write_max_active
zfs_vdev_async_write_min_active
zfs_vdev_cache_bshift
zfs_vdev_cache_max
zfs_vdev_cache_size
zfs_vdev_future_pending
zfs_vdev_max_active
zfs_vdev_max_pending
zfs_vdev_min_pending
zfs_vdev_ramp_rate
zfs_vdev_scrub_max_active
zfs_vdev_scrub_min_active
zfs_vdev_sync_read_max_active
zfs_vdev_sync_read_min_active
zfs_vdev_sync_write_max_active
zfs_vdev_sync_write_min_active
zfs_vdev_time_shift
zfs_write_limit_max
zfs_write_limit_min
zfs_write_limit_override
zfs_write_limit_shift
zil_replay_disable
zil_slog_limit
zio_injection_enabled
zvol_immediate_write_sz
EOP
) | solparamerator
}

solparamerator(){
    sed -e "s/$/\/D /g" | sort | mdb -k 2>/dev/null | grep -v ':$' | awk -F: '{print $1" "$2}' | columnt
}

ziopriorities(){
    # http://www.opensource.apple.com/source/zfs/zfs-59/zfs_kext/zfs/sys/zio.h
    # #define ZIO_PRIORITY_NOW                (zio_priority_table[0])
    # #define ZIO_PRIORITY_SYNC_READ          (zio_priority_table[1])
    # #define ZIO_PRIORITY_SYNC_WRITE         (zio_priority_table[2])
    # #define ZIO_PRIORITY_ASYNC_READ         (zio_priority_table[3])
    # #define ZIO_PRIORITY_ASYNC_WRITE        (zio_priority_table[4])
    # #define ZIO_PRIORITY_FREE               (zio_priority_table[5])
    # #define ZIO_PRIORITY_CACHE_FILL         (zio_priority_table[6])
    # #define ZIO_PRIORITY_LOG_WRITE          (zio_priority_table[7])
    # #define ZIO_PRIORITY_RESILVER           (zio_priority_table[8])
    # #define ZIO_PRIORITY_SCRUB              (zio_priority_table[9])
    echo zio_priority_table+0/V |mdb -k 2>/dev/null |grep -v ':$' |awk '{print $1" "$2" ZIO_PRIORITY_NOW"}'
    echo zio_priority_table+1/V |mdb -k 2>/dev/null |grep -v ':$' |awk '{print $1" "$2" ZIO_PRIORITY_SYNC_READ"}'
    echo zio_priority_table+2/V |mdb -k 2>/dev/null |grep -v ':$' |awk '{print $1" "$2" ZIO_PRIORITY_SYNC_WRITE"}'
    echo zio_priority_table+3/V |mdb -k 2>/dev/null |grep -v ':$' |awk '{print $1" "$2" ZIO_PRIORITY_ASYNC_READ"}'
    echo zio_priority_table+4/V |mdb -k 2>/dev/null |grep -v ':$' |awk '{print $1" "$2" ZIO_PRIORITY_ASYNC_WRITE"}'
    echo zio_priority_table+5/V |mdb -k 2>/dev/null |grep -v ':$' |awk '{print $1" "$2" ZIO_PRIORITY_FREE"}'
    echo zio_priority_table+6/V |mdb -k 2>/dev/null |grep -v ':$' |awk '{print $1" "$2" ZIO_PRIORITY_CACHE_FILL"}'
    echo zio_priority_table+7/V |mdb -k 2>/dev/null |grep -v ':$' |awk '{print $1" "$2" ZIO_PRIORITY_LOG_WRITE"}'
    echo zio_priority_table+8/V |mdb -k 2>/dev/null |grep -v ':$' |awk '{print $1" "$2" ZIO_PRIORITY_RESILVER"}'
    echo zio_priority_table+9/V |mdb -k 2>/dev/null |grep -v ':$' |awk '{print $1" "$2" ZIO_PRIORITY_SCRUB"}'
}

solarcsummary(){
    have arc_summary.pl && run arc_summary.pl arc_summary
}

soltcptuneables(){
    ( \
        tcptuneables="_conn_req_max_q _conn_req_max_q0 _cwnd_max _deferred_acks_max _naglim_def cong_default recv_buf send_buf"
            for p in ${tcptuneables} ; do
                ipadm show-prop -p ${p} tcp 2>/dev/null
            done
        ipadm show-prop -p hostmodel ipv4 ) \
    |sort -V |uniq |egrep -v "^[[:space:]]"
}

solnetwork(){
    have netadm && run 'netadm list' netadm-list
    run soltcptuneables
    if have dladm ; then
        run 'dladm show-phys -m |grep -v ^LINK |sort' dladm-show-phys-m
        if dladm show-phys -L > /dev/null 2>&1 ; then
            run 'dladm show-phys -L |grep -v ^LINK |sort' dladm-show-phys-L
        else
            run 'dladm show-phys |grep -v ^LINK |sort' dladm-show-phys
        fi
        run 'dladm show-link |grep -v ^LINK |sort' dladm-show-link
        run 'dladm show-ether |grep -v ^LINK |sort' dladm-show-ether
        run 'dladm show-linkprop -p flowctrl 2>/dev/null ' dladm-show-linkprop-flowctrl
        for aggr in $(dladm show-aggr -p -o link |sort) ; do
            run 'dladm show-aggr ${aggr}' dladm-show-aggr-${aggr}
            run 'dladm show-aggr -x ${aggr}' dladm-show-aggr-x-${aggr}
            run 'dladm show-aggr -L ${aggr}' dladm-show-aggr-L-${aggr}
            run 'dladm show-aggr -s ${aggr}' dladm-show-aggr-s-${aggr}
            if have dlstat ; then
                run 'dlstat show-aggr ${aggr}' dlstat-show-aggr-${aggr}
            fi
        done
        run 'dladm show-vlan'
        run 'dladm show-vnic'
    fi
    run 'ifconfig -a' ifconfig-a
    if have ipadm ; then
        run 'ipadm show-addr'
        run 'ipadm show-if'
    fi
    if have ipmpstat ; then
        if [ $(ipmpstat -g 2>/dev/null |wc -l) -ge 1 ] ; then
            run 'ipmpstat -gn 2>/dev/null' ipmpstat-gn
            run 'ipmpstat -in 2>/dev/null' ipmpstat-in
            run 'ipmpstat -an 2>/dev/null' ipmpstat-an
        fi
    fi
    if have dlstat ; then
        run 'dlstat show-phys'
    fi
    if [ ${GRABMSGS} -eq 1 ] ; then
        if have dladm ; then
            for net in $(dladm show-link -p -o link |sort) ; do 
                run "dladm show-linkprop ${net}" dladm-show-linkprop-${net}
            done
        fi
        have ipadm && run "ipadm show-prop"
        #kstat -c net
    fi
    have netstat && run 'netstat -f inet -nr'
    for f in hosts resolv.conf netmasks static_routes inet/static_routes inet/static_routes-DefaultFixed nsswitch.conf; do
        if [ -f /etc/${f} ] ; then
            run "egrep -v '^\#|^$' /etc/${f}" etc-${f}
        fi
    done
}
solcluster() {
    if [ -d /usr/cluster/bin ] ; then
        run 'cluster show'
        run 'clrg status'
        run 'clrs status'
        run 'clq status'
        run 'clinterconnect show -v'
        run 'solmapdevices'
        grab /etc/cluster/ccr/global/infrastructure
        #clrg show
        #clrs show
        #cldevice list -v
    fi
}

rsfservicetimegrep(){
    logs=$(ls -tr /opt/HAC/RSF-1/log/rsfmon.log*)
    ggrep -h -E "${1}.*Total run time for service" ${logs}
}
rsfcheckinitscripts(){
    for f in init.d/rsfmonrc rc0.d/K01rsf rc1.d/K01rsf rc2.d/S99rsf rcS.d/K01rsf ; do
        if [ ! -e "/etc/${f}" ] ; then
            run "echo RSF-1 INIT SCRIPT /etc/${f} NOT INSTALLED" "DANGER DANGER"
        fi
    done
}
rsfversion(){
    run "pkginfo |grep rsf-1 |awk '{print \$2}' |xargs -i pkginfo -l {}" rsf-1-version
}
rsfconfig(){
    if [ -f "${rsfconf}" ] ; then
        grab "${rsfconf}"
        if [ -e "/usr/gnu/bin/grep" ] ; then
            #run "LC_COLLATE=C /usr/gnu/bin/grep -n '[^ -~]' ${rsfconf}" 'RSF1-NonASCII-Lines'
            run "pcregrep --color=auto -n \"[\\x80-\\xFF]\" ${rsfconf}" 'RSF1-NonASCII-Lines'
        fi
    fi
}
rsfscsi2reservationcheck(){
    if [ -x ${rsfpath}/bin/rsfcdb ] ; then
        run "rsfcdb list_props" rsfcdb-list_props
        count=$(rsfcdb list_props|awk '/prop_scsi2_drive_count/ {print $NF}')
        if [ -x ${rsfpath}/bin/mhdc ] ; then
            for f in ${rsfpath}/etc/.res_drives* ; do
                [ -e "$f" ] || break
                run "${rsfpath}/bin/mhdc -vd /dev/rdsk/$(gawk 'BEGIN{OFS="s2 /dev/rdsk/"};{$1=$1; print $0}' $f)s2 -c STATUS |grep MHIOCSTATUS," zpool-${z}-SCSI-2-reservation-status
                z=$(basename ${f} |awk -F. '{print $NF}')
                zres=$(gawk -v n=${count} 'NR<=n{print;next}{exit}' RS='[[:blank:]]+|\n' ${f})
                for r in ${zres} ; do
                    if ${rsfpath}/bin/rsfcli -i0 -v heartbeats |grep ${r} >/dev/null 2>&1; then
                        run 'echo "WARNING: RSF-1 reservation/heartbeat disc conflict for ${r}"' RSF-hb-res-conflict-${r}
                    fi
                done
            done
        fi
    fi
}
rsfmoncalls(){
    run "${rsfpath}/bin/rsfmon -v 2>&1" rsfmon-v
    run "${rsfpath}/bin/rsfmon -RR 2>&1" rsfmon-RR
    if rsfmon -v 2>&1 |grep "release 3.7.4" >/dev/null 2>&1 ; then
        run "ls -ltr /opt/HAC/RSF-1/bin/rsfexec*" rsfexec-patch-check
    fi
}
rsfclicalls(){
    if [ -x ${rsfpath}/bin/rsfcli ] ; then
        run "${rsfpath}/bin/rsfcli -i0 -v list 2>/dev/null" rsfcli-list
        run "${rsfpath}/bin/rsfcli -i0 -v heartbeats 2>/dev/null" rsfcli-hearbeat
        run "${rsfpath}/bin/rsfcli -i0 status 2>/dev/null" rsfcli-status
        run "${rsfpath}/bin/rsfcli modes" rsfcli-modes
    fi
}
rsfhostid(){
    if [ -x /opt/HAC/bin/hac_hostid ] ; then
        run /opt/HAC/bin/hac_hostid
    fi
}
rsfgrablic(){
    for lic in ${rsfpath}/etc/licen[c,s]e.* ; do
        if [ -f "${lic}" ] ; then
            grab "${lic}"
        fi
    done
}
rsfgrabpasswd(){
    if [ -f "${rsfpath}/etc/passwd" ] ; then
        grab "${rsfpath}/etc/passwd"
    fi
}
rsfserviceruntimes(){
    for s in $(grep "Total run time for service " /opt/HAC/RSF-1/log/rsfmon.log* |awk '{print $5}' |tr -d \[ |sort |uniq); do
        run "rsfservicetimegrep ${s}" rsf_failover_history-${s}
    done
}
rsfloggrab(){
    if [ ${GRABMSGS} -eq 1 ] ; then
        rsflogs="${rsfpath}/log"
        for log in ${rsflogs}/{rsfmon.log,broken.log.d/*,*.panic.log} ; do
            if [ -f "${log}" ] ; then
                grab "${log}"
            fi
        done
    fi
}

rsfdiags(){
    if ! pkginfo |grep rsf-1 > /dev/null 2>&1 ; then
        return;
    fi
    export rsfpath=/opt/HAC/RSF-1
    export rsfconf=${rsfpath}/etc/config
    rsfcheckinitscripts
    rsfversion
    rsfconfig
    rsfscsi2reservationcheck
    rsfmoncalls
    rsfclicalls
    rsfhostid
    rsfgrablic
    rsfgrabpasswd
    rsfserviceruntimes
    rsfloggrab
}

solprstat(){
    run 'echo |prstat -amv -n 999999 0 1' top
}

solmemconf(){
    if have memconf.pl ; then
        run 'memconf.pl -v' memconf
    elif have memconf ; then
        run 'memconf -v' memconf
    fi
}
cpackies(){
    if have pkginfo ; then
        if pkginfo |grep -i coraid > /dev/null 2>&1 ; then
            for p in $(pkginfo |grep -i coraid |awk '{print $2}') ; do
                run "pkginfo -l ${p} |egrep 'PKGINST:|NAME:|VERSION:|INSTDATE:'" cpackies-${p}
            done
        fi
    fi
}

hmptools(){
    if [ ${solflavor} = nexenta ] ; then
        :
    else
        pkgs="biosdrv hmp-hwmgmt hmp-ipmiflash hmp-ipmitool hmp-libs hmp-snmp hmp-tools hmp-tools-biosconfig hmp-tools-ubiosconfig hmp-utils"
        for p in ${pkgs} ; do
            if pkginfo |grep "${p}" > /dev/null 2>&1 ; then
                run "pkg info -l ${p} 2>/dev/null" hmp-tools-${p}
            fi
        done
    fi
}

nexall(){
    # this is massive -- probably a better way
    if [ ${solflavor} = nexenta ] ; then
        if [ ${GRABMSGS} -eq 1 ] ; then
        have nmc && run 'echo "show all"|nmc' nmc-show-all
        for log in nms.log nmv.log nms-down.log nmcd.log ; do
            if [ -f /var/log/${log} ] ; then
                grab /var/log/${log}
            fi
        done
        fi
    fi
}

soliscsiview(){
    for i in $(stmfadm list-lu | awk -F ':' '{print $2}' | sed 's/^\s//g'); do
        echo "LU Name: ${i}"
        stmfadm list-view -l "${i}"
    done
}

soliscsi(){
    if have itadm ; then
        run 'itadm list-target -v'
        run 'itadm list-tpg -v'
    fi
    if have stmfadm ; then
        run 'stmfadm list-lu -v'
        run 'soliscsiview' stmfadm-list-view
    fi
}

#end solaris
#begin linux
liniostat(){
    have iostat && run "iostat -xdh"
}
whatlinux(){
    run "uname -a" uname-a
    run 'grep . /etc/*release* /etc/*version* | sed 50q' version
}
linmodinfo(){
    run "find /sys/module/aoe -name version | xargs cat" module-name
}
linmounts(){
    grab /proc/mounts
}
linaoe(){
    have aoe-version && run aoe-version
    have aoe-interfaces && run aoe-interfaces
    linnetwork
    for ko in $(find /lib/modules/ -type f -name "aoe.ko") ; do
        run "strings ${ko} |grep -i ^version=" "${ko}"
    done
    if lsmod | grep aoe > /dev/null 2>&1 ; then
        have aoe-stat && run aoe-stat
        linmodinfo
        aoedebugfiles
    fi
}
linlsdevsd(){
    run 'ls -l /dev/sd*' 'SCSI Device enumeration'
}
linmdstat(){
    have mdadm && run "mdadm --detail --scan" mdadm-detail-scan
    [ -e /proc/mdstat ] && grab /proc/mdstat
}
linpvs(){
    #have lvm && run "lvm dumpconfig" lvm-dumpconfig
    have pvs && run pvs
}
linux_vgdisplay(){
    have vgdisplay && run "vgdisplay -v"
}
linnetwork(){
    run 'ifconfig -a'
    have ethtool && linethtool
}
linethtool(){
    for nic in $(find /sys/class/net/*  -type l ! -name lo |awk -F"/" '{print $5}'); do
        run "ethtool -i ${nic};ethtool -k ${nic}; ethtool -g ${nic} ; ethtool -S ${nic}" ethtool-${nic}
    done
}
linfree(){
    run free
}
lindmesg(){
    run 'dmesg | tail -n 100' dmesg
}
linsysctl(){
    run "sysctl -a |sort" sysctl-asort
}
aoedebugfiles(){
    if have aoe-version ; then
        if [ "$(aoe-version | tail -1 | awk '{print $NF}' 2>/dev/null)" -lt 85 ] ; then
            for f in /sys/block/etherd*/debug ; do
                name="$(echo ${f}|sed -e 's/.*\!//' -e 's!/!-!')"
                if [ "${MODE}" = "tar" ] ; then
                    cat "${f}" > ${name}
                else
                    header "${name}"
                    cat "${f}"
                fi
            done
        else
            dmnt=/sys/kernel/debug
            mounted=$(awk '$3=="debugfs"{print $2}' /proc/mounts)
            if [ -z "${mounted}" ] ; then
                if mount -t debugfs none "${dmnt}" ; then
                    imountedit=${dmnt}
                    mounted=${dmnt}
                fi
            fi
            if [ -e ${mounted}/aoe ] ; then
                for f in ${mounted}/aoe/e*.* ; do
                    name="$(echo ${f}| sed -e 's/.*e//')"
                    if [ "${MODE}" = "tar" ] ; then
                        cat "${f}" > "${name}.debug"
                    else
                        header "${f}"
                        cat "${f}"
                    fi
                done
            fi
            if [ -n "${imountedit}" ] ; then
                umount "${dmnt}"
            fi
        fi
    fi
    [ -e /sys/module/aoe/parameters ] && run 'grep . /sys/module/aoe/parameters/*' module-parameters
}
cdmidecode(){
    have dmidecode && run dmidecode
}
lintop(){
    run 'top -b -n1' top
}
chostname(){
    have hostname && run hostname
}

whoisit(){
    have check-hostname && run check-hostname
}

#end linux

# begin coros


fakeuname(){
    run "uname -a | sed -e 's/SunOS/CorOS/'" "uname -a"
}

coros_chassissn(){
    run "json cluster_id < /system/cord/self/devnode.json" ClusterID
}

coros_devnodejson(){
    run 'json -f /system/cord/self/devnode.json' devnode.json
}

coros_platformjson(){
    for f in /cfgstore/config /cfgstore/cord/providers/cord_net\
             /cfgstore/platform/drive.json /cfgstore/platform/mgmt.json\
	     /cfgstore/platform/net.json ; do
	     grab $f
   done
}

coros_dumps(){
    run dumpadm dumpadm
    run 'ls -ltrhF /var/crash/volatile/* 2>/dev/null' crashdumps
}

coros_cores(){
    run coreadm coreadm
    run 'ls -ltrhF /cores/* 2>/dev/null' coredumps
}

coros_rsfdiags(){
    export rsfpath=/opt/HAC/RSF-1
    export rsfconf=${rsfpath}/etc/config
    rsfconfig
    rsfmoncalls
    rsfclicalls
    rsfhostid
    rsfgrablic
    rsfgrabpasswd
    rsfserviceruntimes
    rsfloggrab
}

#end coros

clspci(){
    have lspci && run "lspci -vM 2>/dev/null" lspci-vM
}

cuptime(){
    run uptime
}

grablog(){
    printf .
    if [ -e /var/log/vmkernel.log ] ; then
        grab /var/log/vmkernel.log
    fi
    if [ -f /var/log/messages ] ; then
        grab /var/log/messages
    fi
    if [ "${me}" = "Linux" ] ; then
        if [ -f /var/log/syslog ] ; then
            grab /var/log/syslog
        fi
    fi
    if [ "${me}" = "CorOS" ] ; then
        grab /cordpool/$(cordadm list-admin)/root/var/log/syslog 'admin-zone syslog'
    fi
    if [ -f /var/adm/messages ] ; then
        grab /var/adm/messages
    fi
    if [ "${me}" = "VMkernel" ] ; then
        run "ls -l /var/log/" "ls-l-var-log"
    fi
}

package(){
    echo Complete. >&2
    if [ "${MODE}" = "tar" ] ; then
        cd /tmp
        b="$(basename ${tmpdir})"
        tar cf "${b}.tar" "${b}"
        echo "Output file is /tmp/${b}.tar" >&2
    else
        echo "Output file is ${outfile}" >&2
    fi
}

stamp(){
    run "echo 'Coraid Diags Version: ${VERSION}'" coraid-diags-version
    run "date -u +%Y-%m-%d\ %H:%M\ %Z" date
}

esxdiags(){
    HEADERS=1
    esxversion
    whoisit
    cuptime
    driver
    if [ ${EXTENDED} -eq 1 ] ; then
        targeted
        esxvolume
        esxmpath
        wrapmap
        esxscsidevs
        esxnas
        esxvmknic
        esxvswitch
        esxnics
        lsvms
        esxsnapshotsandvmdkinfo
        esxhwproduct
        esxHV
        esxlspci
        esxmodinfo
        esxstoragerules
        esxdmesg
    fi
}

corosdiags(){
    merooty
    HEADERS=1
    have ntpq && run "ntpq -p"
    chostname
    coros_chassissn
    coros_devnodejson
    whoisit
    cuptime
    fakeuname
    #some sneep replacement?
    #solcstates #?
    driver
    ethdrvadmlistdevicesa
    solsasinfo
    zpoollist
    zpoolgetall
    cdmidecode
    coros_rsfdiags
    cfmfaulty
    cfmdump
    coros_dumps
    coros_cores
    coros_platformjson
}

soldiags(){
    merooty
    solflavors
    HEADERS=1
    have ntpq && run "ntpq -p"
    chostname
    whoisit
    cuptime
    whatsol
    solcstates
    solexplorer
    cpackies
    hmptools
    csig
    driver
    ethdrvadmlistdevicesa
    if [ ${EXTENDED} -eq 1 ] ; then
        targeted
        wrapsolarismapnaa
        #exmapnaa
        soldiskinfo
        zpoollist
        zpoolgetall
        solshare
        solcifsmode
        solsmbusers
        soliscsi
        solsidmap
        #solsidmapdump
        solcpuinfo
        solprstat
        cvmstat
        #soldnlc
        solmemconf
        solmemstat
        solswap
        #zfs_file_data
        #solkmastat
        #run solethdrvstats ethdrv-kstat-kmem_cache
        #solirq
        run solkernparams kernel-parameters
        run solzfsparams zfs-parameters
        #run "ziopriorities |columnt" zfs-io-priorities
        solarcstat
        solarcsummary
        #kstatanalyze
        #solsar
        soltuning
        #solintrstat
        solnetwork
        solipf
        solyp
        solsmarthost
        solcron
        csvcs
        solretired
        cscanpci
        clspci
        #fmtopo
        cdmidecode
        cprtdiag
        solipmitool
        solfw
        solilom
        lsiscan
        #lsidisks
        solcluster
        rsfdiags
        #fmstatus
        #fmadmconfig
        cfmfaulty
        cfmdump
        solEClogs
        soldumps
        solcores
        nexall
        #ethercloud
    fi
}

lindiags(){
    HEADERS=1
    chostname
    whatlinux
    whoisit
    cuptime
    if [ -e /proc/ethdrv ] ; then
        driver
        #targeted
    fi
    linaoe
    linfree
    linmounts
    linpvs
    linux_vgdisplay
    linmdstat
    linlsdevsd
    if [ ${EXTENDED} -eq 1 ] ; then
        lintop
        cvmstat
        liniostat
        clspci
        lsiscan
        linsysctl
        cdmidecode
    fi
}

me=$(uname)

[ -e "/bin/vmware" -o -e "/usr/bin/vmware" ] && me=VMkernel
grep -i coros /etc/release > /dev/null 2>&1 && me=CorOS

export $me

case ${me} in
    VMkernel)
        PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
        ;;
    SunOS)
        PATH=/usr/gnu/bin:/usr/cluster/bin:/usr/bin:/usr/sbin:/bin:/sbin:/opt/coraid/bin:/opt/HAC/RSF-1/bin:/usr/lib/fm/fmd
        ;;
esac
export PATH

if [ -n "${EXEX}" ] ; then
    stamp
    driver 1>/dev/null
    eval "${EXEX}"
    exit 0
fi

if [ ! "${MODE}" = local ] ; then
    stamp

    case ${me} in
	CorOS)
	    corosdiags
	    ;;
        VMkernel)
            esxdiags
            ;;
        SunOS)
            soldiags
            ;;
        Linux)
            merooty
            lindiags
            ;;
    esac
    if [ ${GRABMSGS} -eq 1 ] ; then
        grablog
    fi

    package
else
    targeted
fi
