#!/bin/bash

# shellcheck shell=sh
# shellcheck disable=SC2034 
# shellcheck disable=SC2059
# shellcheck disable=SC1091
# shellcheck disable=SC1090
# shellcheck disable=SC2116

set -e
#set -x

if [ "$(id -u)" -ne 0 ]; then
	echo "$0 needs root: please use sudo."
	exit 1
fi

# Source Auxilium (args parser)
. /usr/share/auxilium/auxilium.sh

auxilium_init "$(basename "$0")" -m 'Displays list of devices and their physical location'

auxilium_add redmine -s r -t opt -m 'Format for redmine'
auxilium_add field -s f -t str -l "id|mount_point|majmin|scsi|vendor|serial|model|firmware|size|description|fo_name|kname" -d "serial" -m 'Field to display under Device Name'
auxilium_add csv -t opt -m 'Return a CSV formatted list of devices (id,kname,mount-point,scsi,majmin,status,vendor,model,serial,firmware,size,description)'
auxilium_add locate -t positional -a -m 'List of device to locate (sdx or BoxXDiskX)'


if [ -f "/usr/share/ferreus-orbit/common.sh" ]; then
	. "/usr/share/ferreus-orbit/common.sh"
elif [ -f "share/common.sh" ] ; then
	. "share/common.sh"
elif [ -f "../share/common.sh" ] ; then
	. "../share/common.sh"
else
	echo "Cannot load common.sh: exiting"
	exit 1
fi

auxilium_parse "$@"

fo_lock

fo_get_name(){
	width="$2"
	locate="False"
	fo_name="$1"
	# shellcheck disable=SC2046
	# shellcheck disable=SC2005
	fullname=$(echo $(fo_get_disk_info "${fo_name}" mount_point)|awk '{print $1}')
	name=$(basename "${fullname}")
	# shellcheck disable=SC2154
	locate=$(fo_contain "$AUXILIUM_ARG_locate" "${name}")
	mount | grep -q "${fullname}" || name="${UNMOUNTED}${name}"
	fo_center_align "$width" "$locate" "$name"
}

fo_get_field(){
	fo_name="$1"
	# shellcheck disable=SC2154
	field="$AUXILIUM_ARG_field"
	# name=$(fo_get_disk_info "${fo_name}" mount_point)
	# [ -z "$name" ] && name=$(fo_get_disk_info "${fo_name}" kname)
	shortname=$(basename "${fo_name}" 2>/dev/null)
	f=$(fo_get_disk_info "${fo_name}" "${field}")
	echo "$f"
}

fo_format_textile(){
	unset fo_format_text fo_format_locate
	# shellcheck disable=SC2086
	fo_format_text=$(echo $1)
	fo_format_locate=$2
	if [ -z "$fo_format_locate" ] || [ "$fo_format_locate" -eq 0 ]; then
		echo "$fo_format_text"
	else
	 echo "<{background:red;color:white;font-weight:bold}.${fo_format_text}"
	fi
}

fo_display_array_textile(){
	unset header footer
	if [ "$1" = "--header" ]; then
		header='True'
		shift 1
	fi
	fo_name="$1"
	k_name="$2"
	size="$3"
	[ "${size}" = "null" ] && size=0
	model="$4"
	sn="$5"
	fw="$6"
	descr="$7"
	if [ -n "${header}" ]; then
		printf -- "|_.%s|_.%s|_.%s|_.%s|_.%s|_.%s|\n" "$fo_name" "$size" "$model" "$sn" "$fw" "$descr"
	else
		unset to_locate
		if [ -z "$fo_name" ]; then
			if [ -b "$k_name" ]; then
				eval "$(udevadm info -q property --export "${k_name}")"
				fo_name="/srv/node/$(fo_get_sorted_name)"
			else
				fo_name="Unmounted"
			fi
		fi
		short_fo=$(basename "${fo_name}" 2>/dev/null)
		if [ -n "${fo_name}" ] && [ "$(fo_contain "${AUXILIUM_ARG_locate}" "${short_fo}")" -eq 1 ]; then
			to_locate=1
		fi
		printf -- "|%s|%s|%s|%s|%s|%s|\n"\
						"$(fo_format_textile "$fo_name" "$to_locate")"\
						"$(fo_format_textile "$size" "$to_locate")"\
						"$(fo_format_textile "$model" "$to_locate")"\
						"$(fo_format_textile "$sn" "$to_locate")"\
						"$(fo_format_textile "$fw" "$to_locate")"\
						"$(fo_format_textile "$descr" "$to_locate")"
	fi
}

fo_display_array(){
	unset header footer
	if [ "$1" = "--header" ]; then
		header='True'
		shift 1
	elif [ "$1" = "--footer" ]; then
		footer='True'
		shift 1
	fi
	fo_name="$1"
	k_name="$2"
	size="$3"
	[ "${size}" = "null" ] && size=0
	model="$4"
	sn="$5"
	fw="$6"
	descr="$7"
	color_begin=''
	color_end=''
	arrow=''
	to_locate=0
	lentotal=$((LEN_MODEL + LEN_SN + LEN_MOUNT + 52))
	lenm=$LEN_MOUNT
	if [ -n "${header}" ]; then
		fo_repeat_char '_' $lentotal;echo
		printf -- "|%-${lenm}s|%-15s|%-${LEN_MODEL}s|%-${LEN_SN}s|%-10s|%-20s|\n" "$fo_name" "$size" "$model" "$sn" "$fw" "$descr"
		printf -- "|$(fo_repeat_char '-' "${lenm}")|---------------|$(fo_repeat_char '-' "${LEN_MODEL}")|$(fo_repeat_char '-' "${LEN_SN}")|----------|--------------------|\n"
	elif [ -n "${footer}" ]; then
		fo_repeat_char '¯' $lentotal;echo ' '
	else
		if [ -z "$fo_name" ]; then
			if [ -b "$k_name" ]; then
				eval "$(udevadm info -q property --export "${k_name}")"
				fo_name="/srv/node/$(fo_get_sorted_name)"
			else
				fo_name="Unmounted"
			fi
		fi
		short_fo=$(basename "${fo_name}" 2>/dev/null)
		short_k=$(basename "${k_name}" 2>/dev/null)
		if [ -n "${fo_name}" ] && [ "$(fo_contain "${AUXILIUM_ARG_locate}" "${short_fo}")" -eq 1 ]; then
			to_locate=1
		fi
		if [ "$to_locate" -eq 1 ];then
			color_begin="${RED}"
			color_end="${NORM}"
		fi
		printf -- "|${color_begin}%-${lenm}s|%-15s|%-${LEN_MODEL}s|%-${LEN_SN}s|%-10s|%-20s${color_end}|\n" "${short_fo}" "${size}" "$model" "$sn" "$fw" "$descr"
	fi
}

main(){
	if [ -z "$AUXILIUM_ARG_sh_completion" ]; then
		fo_init clean
	fi

	if [ -n "$AUXILIUM_ARG_locate" ]; then
		for i in $AUXILIUM_ARG_locate; do
			grep -q "/srv/node/${i}" "$FO_CACHE_DISKS_INFOS"|| fo_write_by_fo_name "/srv/node/${i}"
		done
	fi
	if [ -z "$AUXILIUM_ARG_csv" ]; then
		if [ -z "$AUXILIUM_ARG_redmine" ]; then
			LEN_SN=15
			LEN_MODEL=18
			LEN_MOUNT=11
			while IFS="," read -r id raid_path kname mount_point fo_name scsi majmin vendor model serial fw size descr
			do
				[ "${#serial}" -gt "$LEN_SN" ] && LEN_SN=${#serial}
				[ "${#model}" -gt "$LEN_MODEL" ] && LEN_MODEL=${#model}
				mp=$(basename "$mount_point")
				[ "${#mp}" -gt "$LEN_MOUNT" ] && LEN_MOUNT=${#mp}
			done < "$FO_CACHE_DISKS_INFOS"
			fo_display_array --header "Mount Point" "" Size Model Serial Firmware Description

			sort -t ',' -k 4 -o "$FO_CACHE_DISKS_INFOS" "$FO_CACHE_DISKS_INFOS"
			while IFS="," read -r id raid_path kname mount_point fo_name scsi majmin vendor model serial fw size descr
			do
				fo_display_array "$mount_point" "$kname" "$size" "$model" "$serial" "$fw" "$descr"
			done < "$FO_CACHE_DISKS_INFOS"
			fo_display_array --footer;echo
			sort -t ',' -k 1 -o "$FO_CACHE_DISKS_INFOS" "$FO_CACHE_DISKS_INFOS"
			LEN_FIELD=18
			[ "$AUXILIUM_ARG_field" = "serial" ] && LEN_FIELD=$LEN_SN
			[ "$AUXILIUM_ARG_field" = "model" ] && LEN_FIELD=$LEN_MODEL
			underscore=$(fo_repeat_char '_' "${LEN_FIELD}")
			minus=$(fo_repeat_char '-' "${LEN_FIELD}")
			higher=$(fo_repeat_char '¯' "${LEN_FIELD}")
			FO_DISPOSITION=$(printf "${FO_DISPOSITION}"|sed "s%{UNDERSCORE}%${underscore}%g")
			FO_DISPOSITION=$(printf "${FO_DISPOSITION}"|sed "s%{MINUS}%${minus}%g")
			FO_DISPOSITION=$(printf "${FO_DISPOSITION}"|sed "s%{HIGHER}%${higher}%g")
			while IFS="," read -r id raid_path kname mount_point fo_name scsi majmin vendor model serial fw size descr
			do
				n=$(fo_get_name "$fo_name" "${LEN_FIELD}")
				f=$(fo_get_field "$fo_name")
				unset pfx
				for fi in $f; do
					shortname=$(basename "$mount_point")
					fie=$(fo_center_align "${LEN_FIELD}" "$(fo_contain "$AUXILIUM_ARG_locate" "$shortname")" "$fi")
					FO_DISPOSITION=$(printf "${FO_DISPOSITION}"|sed "s%{${fo_name}}%${n}%" 2>/dev/null)
					FO_DISPOSITION=$(printf "${FO_DISPOSITION}"|sed "s%{SN${pfx}_${fo_name}}%${fie}%" 2>/dev/null)
					pfx="2"
				done
			done < "$FO_CACHE_DISKS_INFOS"
			# final replace {new_line} by \n and @ by \
			# shellcheck disable=SC1003
			FO_DISPOSITION=$(printf "${FO_DISPOSITION}"|sed "s%{new_line}%\n%g"| tr '@' '\\')
			printf "${FO_DISPOSITION}\n"
		else
			fo_textile_file=$(mktemp)
			fo_display_array_textile  --header "Mount Point" "" "Size" "Model" "Serial" "Firmware" "Description" > "$fo_textile_file"
			sort -t ',' -k 4 -o "$FO_CACHE_DISKS_INFOS" "$FO_CACHE_DISKS_INFOS"
			while IFS="," read -r id raid_path kname mount_point fo_name scsi majmin vendor model serial fw size descr
			do
				fo_display_array_textile "$mount_point" "$kname" "$size" "$model" "$serial" "$fw" "$descr" >> "$fo_textile_file"
			done < "$FO_CACHE_DISKS_INFOS"
			sort -t ',' -k 1 -o "$FO_CACHE_DISKS_INFOS" "$FO_CACHE_DISKS_INFOS"
			while IFS="," read -r id raid_path kname mount_point fo_name scsi majmin vendor model serial fw size descr
			do
				f=$(fo_get_field "$fo_name")
				unset fo_pfx fo_txt fo_to_locate fo_unmounted
				for fi in $f; do
					shortname=$(basename "$mount_point")
					mountpoint -q "${mount_point}" || fo_unmounted=true
					echo A$mount_point $fo_unmounted >&2
					fo_to_locate="$(fo_contain "$AUXILIUM_ARG_locate" "$shortname")"
					# shellcheck disable=SC2086
					fie=$(echo $fi)
					fo_txt="*${shortname}*"
					mountpoint -q "${mount_point}" || fo_txt="-${fo_txt}-"
					fo_txt="${fo_txt}\n${fie}"
					if [ "$fo_to_locate" -eq 1 ]; then
						fo_noborder_txt="={border:0;border-top:1px solid black;font-weight;bold;background:red;color:white}.${fo_txt}"
						fo_txt="={font-weight;bold;background:red;color:white}.${fo_txt}"
					else
						fo_noborder_txt="={border:0;border-top:1px solid black}.${fo_txt}"
						fo_txt="=.${fo_txt}"
					fi
					FO_TEXTILE=$(printf "${FO_TEXTILE}"|sed "s%{${fo_name}${fo_pfx}}%${fo_txt}%")
					FO_TEXTILE_NOBORDER=$(printf "${FO_TEXTILE_NOBORDER}"|sed "s%{${fo_name}${fo_pfx}}%${fo_noborder_txt}%")
					fo_pfx="_2"
				done
			done < "$FO_CACHE_DISKS_INFOS"
			# shellcheck disable=SC1003
			[ -n "$FO_TEXTILE_NOBORDER" ] && printf "${FO_TEXTILE_NOBORDER}\n"|sed "s%{new_line}%\n%g"| tr '~' '&'|tr '!' '\\'|tr '@' '%' >> "$fo_textile_file"
			# shellcheck disable=SC1003
			printf "${FO_TEXTILE}\n"|sed "s%{new_line}%\n%g"| tr '~' '&'|tr '!' '\\'|tr '@' '%' >> "$fo_textile_file"
			cat "$fo_textile_file"
			rm "$fo_textile_file"
		fi
	else
		cat "$FO_CACHE_DISKS_INFOS"
	fi
}

main