#!/bin/sh
# 60 # timeout of 60 seconds

# Script for reading details of all available storage devices V3
# Written by Chris Mocock, Sam Kellett and Andy Henson
# Copyright (C) 2012,2015 Wavestore Ltd
# Copyright (C) 2016 New Zexia Ltd
#
# This is the V3 version (output format), (but it also supports V2 in legacy mode)
# This is the script for Wavestore-el7 systems and it handles MegaRaid cards
#
# The first line output is a format version number - V3 in this case
#
# Subsequent lines are formatted with spacing with the following format:
# PATH DISPLAY MOUNT-POINT CAPACITY PARENT %USED MODEL SERIAL STATUS
#
# For example:
# V3
# /dev/disk/by-path/pci-0000:00:1f.2-scsi-0:0:0:0              sda   N/A        250.1GB    -    N/A    WDCWD2500BPVT-00JJ5T0    WD-WXF1EC1ADMTD      SYSTEM
# /dev/disk/by-path/pci-0000:00:1f.2-scsi-0:0:0:0-part1        sda1  /          15.7GB     sda  N/A    WDCWD2500BPVT-00JJ5T0    WD-WXF1EC1ADMTD      SYSTEM
# /dev/disk/by-path/pci-0000:00:1f.2-scsi-0:0:0:0-part2        sda2  /var/log   125MB      sda  N/A    WDCWD2500BPVT-00JJ5T0    WD-WXF1EC1ADMTD      SYSTEM
# /dev/disk/by-path/pci-0000:00:1f.2-scsi-0:0:0:0-part3        sda3  swap       268MB      sda  N/A    WDCWD2500BPVT-00JJ5T0    WD-WXF1EC1ADMTD      SYSTEM
# /dev/disk/by-path/pci-0000:00:1f.2-scsi-0:0:0:0-part4        sda4  N/A        233.9GB    sda  N/A    WDCWD2500BPVT-00JJ5T0    WD-WXF1EC1ADMTD      FORMATTED
# /dev/disk/by-path/pci-0000:00:1f.2-scsi-1:0:0:0              sdb   N/A        2000.4GB   -    N/A    WDCWD2003FYYS-02W0B1     WD-WMAY04789224      FORMATTED
# /dev/disk/by-path/pci-0000:00:1f.2-scsi-2:0:0:0              sdc   N/A        750.2GB    -    N/A    ST3750640SV              5QD2R9QW             NOT_FORMATTED
# /dev/disk/by-path/pci-0000:03:00.0-scsi-1:0:0:0              sr0   N/A        N/A        -    N/A    OptiarcDVDRWAD-5280S     N/A                  CDROM
#
# Note that the above output will probably line-wrap on your screen as the lines are long!

# if running in legacy V2 mode, then PARENT is replaced by N/A and DISPLAY is replaced by TARGET
# For example:
# V2
# /dev/disk/by-path/pci-0000:00:1f.2-scsi-0:0:0:0            /dev/sda   N/A        250.1GB    N/A   WDCWD2500BPVT-00JJ5T0    WD-WXF1EC1ADMTD      SYSTEM

# run as "get-disks V3" to use new V3 mode
# otherwise it defaults to legacy V2 mode
VERSION="$1"
if [ "$VERSION" != "V3" ]; then
	VERSION="V2"
fi

#find mapping to of disk names to VD and DG
declare -a VDN	#VD disk name from VDindex
declare -a VDG	#VD from DG
declare -a DGV	#DG from VD
declare -a DGSTATE

# DO NOT CHANGE THESE STRINGS!!!
# These strings are used for output and will be used by the client.
# They need to be stable since they will be translated within the
# client translation system.
strings()
{
	STR_NA="N/A"
	STR_FORMATTED="FORMATTED"
	STR_UNFORMATTED="NOT_FORMATTED"
}

vars()
{
	TARGET=$STR_NA
	DISPLAY=$STR_NA
	CAPACITY=$STR_NA
	MNTPOINT=$STR_NA
	MODEL=$STR_NA
	SERIAL=$STR_NA
	PCUSED=$STR_NA
	FORMATTED=$STR_NA
	PARENT="-"
	EXCLUDE=false
	# We figure out the swap partition once since we can't do it with the
	# method we use in getMntPoint()
	SWAP=`/bin/cat /proc/swaps | /usr/bin/tail -n 1 | /bin/sed s/\ .*//`
}

printfFormattedLine()
{
	if [ $VERSION == "V3" ]; then
		/usr/bin/printf "%-62s %-10s %-10s %-10s %-6s %-6s %-24s %-20s %s\n" \
			$DISK $DISPLAY $MNTPOINT $CAPACITY $PARENT $PCUSED $MODEL $SERIAL $FORMATTED
	else
		[ -z "$TARGET" ] && TARGET="/$DISPLAY"
		/usr/bin/printf "%-60s %-10s %-10s %-10s %-6s %-24s %-20s %s\n" \
			$DISK $TARGET $MNTPOINT $CAPACITY $PCUSED $MODEL $SERIAL $FORMATTED
	fi

}

sasdisks()
{
#delete any serial numbers over 1h old
find /dev/disk/to-serial -mmin +60 -delete &>/dev/null

#set array of VD[] to map virtual drives to 
VDISKS=`ls /dev/disk/by-path/*scsi-0:2* 2>/dev/null`
if [ "$VDISKS" ]; then
while read A
do
	#echo A=$A
	# get the virtual disk index part of the string, which is after 0:2: if it's MegaRAID
	VDI=${A#*scsi-0:2:}
	# and strip off all after the :
	VDI=${VDI%:*}
	# now look up the disk name from the link
	D=`readlink -f $A 2>/dev/null`
	# and store the Virtual Disk Name for this index
	VDN[$VDI]=${D#/dev/}
	#echo "VDN[$VDI]=${VDN[$VDI]}"
done <<<"$VDISKS"
fi

#and set array of DG (disk group) to VD (virtual drive) mapping
VALL=`/usr/share/venusd/EXEC/storcli /call/vall show | grep "^[0-9]"`
if [ "$VALL" ]; then
while read A B STATE D
do
	DGI=${A%/*}
	VDI=${A#*/}
	DGN[$DGI]="${VDN[$VDI]}"
	DGV[$VDI]=$DGI
	DGSTATE[$DGI]=$STATE
	#echo "DGSTATE[$DGI] = $STATE"
	#echo "VDN[$VDI]=${VDN[$VDI]}"
	#echo "DGV[$VDI]=${DGV[$VDI]}"
	#echo "DGI=$DGI VDI=$VDI VDN[$VDI]=${VDN[$VDI]} DGN[$DGI]=${DGN[$DGI]}"
done <<<"$VALL"
fi

#now read all disk info
SALL=`/usr/share/venusd/EXEC/storcli /call show | grep SATA`
if [ "$SALL" ]; then
while read A X1 X2 X3 CAP CAP2 X4 X5 X6 X7 X8 M1 M2 X10; do
	E=${A/:*/}
	S=${A/*:/}
	DISK=/se${E}s$S
	TARGET=$DISK
	DISPLAY=se${E}s$S
	if [ -f /dev/disk/to-serial/$DISK ]; then
		SERIAL=`cat /dev/disk/to-serial/$DISK`
	else
		#we read the serial if it's not taking too long
		if [ "$SECONDS" -gt 10 ]; then
			SERIAL="-"
			mkdir /dev/disk/to-serial
		else
			SERIAL=`/usr/share/venusd/EXEC/storcli /c0/e${E}/s${S} show all | grep SN | sed "s/SN = *//"`
			if [ "$SERIAL" -a -d /dev/disk/to-serial ]; then
				echo $SERIAL >/dev/disk/to-serial/$DISK
			fi
		fi
	fi
	if [ -z "$SERIAL" ]; then
		SERIAL="-"
	fi
	#sometimes the model number is in two parts, sometimes just one.
	#If X10 does not exist we want MODEL1 as model number otherwise we just want MODEL
	if [ -z "$X10" ]; then
		MODEL=$M1
		X10=$M2
	else
		MODEL=$M2
	fi
	CAPACITY=$CAP$CAP2
	MNTPOINT=N/A
	PARENT="-"
	FORMATTED=${X2^^}
	if [ "$FORMATTED" == "ONLN" ]; then
		FORMATTED="GOOD"
	fi
	if [ "$X3" != "-" -a "$X3" != "F" ]; then
		#x3 is a DG index, look up the name
		PARENT=${DGN[$X3]}
		#fallback incase DG not known
		[ -z "$PARENT" ] && PARENT=dg$X3
		if [ "$FORMATTED" == "RBLD" ]; then
			DGSTATE[$X3]="REBUILDING"
		fi
	fi
	#we should remove this and add a 'RBLD' state for drives
	#but leave it for now as it makes system work
	if [ "$FORMATTED" == "RBLD" ]; then
		FORMATTED="GOOD"
	fi
	if [ "$FORMATTED" != "JBOD" ]; then
		printfFormattedLine
	fi
done <<<"$SALL"
fi
}

main()
{
	strings
	vars
	/bin/echo $VERSION

	#show any disks hidden behind RAID controller cards
	sasdisks

	# now list normal disks
	/usr/share/venusd/EXEC/createByPath.sh >/home/dvr/createByPath.txt 2>/dev/null
	for D in `/bin/ls /dev/disk/by-path/`; do
		/usr/sbin/partprobe /dev/disk/by-path/$D &>/dev/null
	done

	# an array to remove duplicates
	declare -A DT

	# List all by-paths
	/bin/ls /dev/disk/by-path | /bin/awk '{ print "/dev/disk/by-path/" $1 }' > .disks

	#and include any nfs shares added by nfsadd command
	/bin/cat /etc/nfs.share 2>/dev/null >>.disks

	while read DISK; do
		getAll $DISK
		if [ "$EXCLUDE" = true -o "${DT[$DISPLAY]}" = 1 ]
		then
			EXCLUDE=false
			continue
		fi
		if [ "${TARGET:0:4}" = "/dev" ]; then
			DT[$DISPLAY]=1
		fi
		printfFormattedLine
	done < .disks
	rm -rf .disks &> /dev/null
}

getAll()
{
	if [ "${DISK/:*/}" == "nfs" ]; then
		#specials for nfs disks
		getAllNFS
		return
	fi

	# normal disk, 3ware, or iSCSI
	getTarget $1

	# filter out extended partitions
	if (fdisk -l | grep "^$TARGET .* Extended$" >/dev/null 2>&1)
	then
		EXCLUDE=true
		return
	fi

	getCapacity $1
	getMntPoint $1
	getParent $1
	getModel $1
	getSerial $1

	#now get status - formatted or other
	testFormatted $1
	testSystem $1
	getPcused $1
}

getTarget()
{
	TARGET=`/bin/readlink -f $1`
	if [ -z $TARGET ]; then
		TARGET=$STR_NA
		return 1
	fi
	DISPLAY=${TARGET#/dev/}
}

getCapacity()
{
	CAPACITY=`/sbin/fdisk -l $1 2>/dev/null | /usr/bin/head -n 2 \
		| /usr/bin/tail -n 1 | /bin/awk '{print $3 $4}' | tr -d ','`
	if [ -z $CAPACITY ]; then
		CAPACITY=$STR_NA
		return 1
	fi
}

# Note: Requires that TARGET has already been set for this disk
getMntPoint()
{
	if [ "$TARGET" = "$SWAP" ]; then
		MNTPOINT="swap"
		return
	fi

	# Check if current target is a physical volume
	if pvdisplay | grep "PV Name.* $TARGET$" 2>&1 >/dev/null ; then
		MNTPOINT="LVM"
		return
	fi

	MNTPOINT=`mount | /bin/grep "$TARGET " | /bin/sed s/.*on\ // | /bin/sed s/\ .*//`
	if [ -z $MNTPOINT ]; then
		MNTPOINT=$STR_NA
	fi
}

getModel()
{
	/sbin/lspci | /bin/grep 3ware | /bin/grep ${1:27:7} &>/dev/null
	if [ $? -eq 0 ]; then
		if [[ -x /usr/sbin/tw_cli ]]; then
			is_3wraid=true
			MODEL=`/usr/sbin/tw_cli /c${1:31:1} show Model | /bin/grep -oE "[^=]+$"`
		else
			is_3wraid=false
		fi
	else
		is_3wraid=false
		MODEL=$(/usr/bin/lsblk -dn $1 -o vendor,model | sed 's/ \{1,\}/-/g')
	fi

	if [ -z "$MODEL" ]; then
		MODEL=$STR_NA
		return 1
	fi
}

# Note: Requires getModel has already been run.
getSerial()
{
	if [ $is_3wraid = true ]; then
		SERIAL=`/usr/sbin/tw_cli /c${1:31:1}/u${1:44:1} show Name | \
                /bin/grep -oE "[^=]+$" | sed -e 's/^ *//g' -e 's/ *$//g' | tr ' ' '_'`
		key=n

		if [ -z $SERIAL ]; then
			port=`/usr/sbin/tw_cli /c${1:31:1} show | /bin/grep ^p[0-9] \
				| /bin/awk '{print $1, $3}' | /bin/grep "u${1:44:1}" \
				| /usr/bin/head -1 | /bin/awk {'print $1'}`
			SERIAL=`/usr/sbin/tw_cli /c${1:31:1}/$port show Serial | /bin/grep -oE "[^=]+$"`

			key=s
		fi
	else
		SERIAL=$(lsblk -dn $1 -o serial)
		key=s
	fi

	if [ -z "$SERIAL" ]; then
		SERIAL=$STR_NA
		return 1
	else
		SERIAL=`/bin/echo $SERIAL | /bin/sed "s/^/$key/g"`
	fi
}

testFormatted()
{
	if [ "$VERSION" != "V3" ]; then
		/usr/bin/mklass -v $* | /bin/grep "Superblock.*ok" &>/dev/null
		res=$?
		if [ $res -eq 0 ]; then
			FORMATTED=$STR_FORMATTED
		else
			FORMATTED=$STR_UNFORMATTED
		fi
	else
		FORMATTED="ASK"
	fi
}

testSystem()
{
	#we need to filter out certain disks and set the status ($FORMATTED) to "SYSTEM"
	#(a) CDROMs which have TARGET paths of /dev/sr... on el7
	#(b) small -part1 partitions which are boot partitions on >4TB disks
	#(c) the system partitions which have mount points, or LVM or swap
	#(d) the system disk; any disk which contains partitions
	#(e) any MegaRAID array that is configured elsewhere (-scsi:0:2)
	if [ "${TARGET:0:7}" = "/dev/sr" ] ; then	#case (a)
		FORMATTED="CDROM"
	elif [[ "$1" == *"-part1" ]]; then		#case (b)
		FORMATTED="SYSTEM"
	elif [ "${MNTPOINT:0:1}" = "/" -o "${MNTPOINT}" = "LVM" -o "${MNTPOINT}" = "swap" ]; then		#case (c)
		FORMATTED="SYSTEM"
	elif /bin/grep ${1}-part .disks >/dev/null; then		#case (d)
		FORMATTED="SYSTEM"
	elif [[ "$1" == *"-scsi-0:2"* ]]; then		#case (e)
		FORMATTED="ARRAY"
		VDI=${1#*scsi-0:2:}
		VDI=${VDI%:0}
		DGI="${DGV[$VDI]}"
		STATE="${DGSTATE[$DGI]}"
		#echo "testSystem ARRAY VDI=$VDI DGI=$DGI DGSTATE=${DGSTATE[$DGI]}"
		if [ "$STATE" == "Dgrd" -o "$STATE" == "Pdgd" ]; then
			FORMATTED="DEGRADED"
		fi
		if [ "$STATE" == "OfLn" ]; then
			FORMATTED="FAILED"
		fi
		if [ "$STATE" == "REBUILDING" ]; then
			FORMATTED="REBUILDING"
		fi
	fi
}

getPcused()
{
	#sets PCUSED
	#for mounted system drives uses df, otherwise na
	if [ "${MNTPOINT:0:1}" = "/" ]; then
		PCUSED=`df -P $TARGET | awk '{print $5}' | tail -n1`
		[ -z "$PCUSED" ] && PCUSED=$STR_NA
	else
		PCUSED=$STR_NA
	fi
}

getParent()
{
	#gets parent of partition drives; DISPLAY should already be set
	#otherwise sets to -
	#nb: sas subsystem drives have separate code for this feature
	PARENT="-"
	if [[ "$1" == *"-part"* ]]; then
		#it's a partition; expect DISPLAY name to end with 1..6
		#so strip off digit to make parent drive
		PARENT=${DISPLAY%[0-9]}
	fi
}

#sets all the parameters for NFS disks
getAllNFS()
{
	#work out if we've assigned a disk letter
	DISKLETTER=`/usr/bin/extract.pl [DiskName | grep $DISK | sed "s/=.*//" | sed s/Disk//`
	#we set the TARGET to a brief nfs name since it's a short field
	TARGET=${DISK#nfs://}
	TARGET=nfs://${TARGET/:*/}
	[ "$DISKLETTER" ] && TARGET="$TARGET($DISKLETTER)"
	DISPLAY=$TARGET
	MOUNTPOINT=/mnt/disk$DISKLETTER
	MOUNTDISK=$MOUNTPOINT/disk${DISKLETTER}.lass
	#we claim it's not mounted because that prevents DiskMaintenance using it
	MNTPOINT=$STR_NA
	#we don't have model/serail for nfs so we put the full NFS string here so the user sees it
	MODEL=$DISK
	SERIAL=$STR_NA
	#we can discover the capacity and things if it's mounted
	#but if it's mounted it might be in use so we need to be careful not to unmount it!
	if [ -f $MOUNTDISK ]; then
		#it's mounted, be careful and use the mountpath
		CAPACITY=`/bin/ls -lh $MOUNTDISK | /bin/cut -d' ' -f5`B
		testFormatted $MOUNTDISK
	else
		#it's not mounted, so we use the nfs://... path
		#we can find if it's formatted by using the fact mklass automounts the disk
		#but betware it also auto unmounts it too!
		CAPACITY=$STR_NA
		testFormatted $DISK get-disks $DISKLETTER
	fi
}

main
