#!/bin/bash
GREP="grep -i"    # default grep with a parameters to find help sections, it may be "agrep, egrep etc". 
USELESS=yes
REV_COLUMNS='no'  # interchange columns position
INTERACTIVE='no'  # interactive mode

# add $PWD into $PATH for test runs of termhelper from local directory
. termhelper-functions || { echo "termhelper-functions not found!" && exit 1 ;}
_th_set_defconfig
_th_load_config

mark_color=green    # color of second column
def_color=default   # default text color
separ=' '           # columns separator (space, '_', '.')
column_width=45	    # width of "code" column
header_width=0	    # header width

MSG01="$(_th_gettext -s "matches several subsections")"
MSG02="$(_th_gettext -s "not found")"
MSG03="$(_th_gettext -s "Hi! Today is")"
MSG04="$(_th_gettext -s "Subsections")"
MSG05="$(_th_gettext -s "Found in")"
MSG06="$(_th_gettext -s "Enter subpart number")"
MSG07="$(_th_gettext -s "Error: must be number of subpart")"
MSG08="$(_th_gettext -s "Error: wrong number")"


= () { 
	color=$1
	eval echo -en "\$$color"
}
= default

if [ "$1" != '-' ] ; then
	prefix=$(echo $LANGUAGE |cut -f1 -d . |cut -f1 -d _)
	[ ${#prefix} -ne 2 ] && prefix=$(echo $LANG |cut -f1 -d . |cut -f1 -d _)
	[ ${#prefix} -ne 2 ] && prefix=$(echo $LC_MESSAGES |cut -f1 -d . |cut -f1 -d _)
	HELPDIR=/usr/share/termhelper/$prefix
	[ -d $HELPDIR ] || HELPDIR=/usr/share/termhelper/en
	[ -d ./helps/$prefix ] && HELPDIR=./helps/$prefix 		# for testing from git project
	STARTFILE=$(ls -1 $HELPDIR |grep -v '\.' |tail -n1)		# file with no dot is a top section of catalogue
fi

_ () {
local lenstr=0 lenstr_=0 str='' color_changed left right=' ' line
if [ "$REV_COLUMNS" == 'yes' ] ; then
	column_2="$1" ; column_1="$2"
	if [ "$color" == "$def_color" ] ; then
		= $mark_color
		color_changed=yes
	fi
	if [ ${#column_1} -ge $((80 - "$column_width"))  ] ; then
		long "$column_1"
		left=''
	else
		echo -n "$column_1"
		left="$column_1"
	fi
	[ "$color_changed" ] && = default
	if [ ${#column_2} -ge $((80 - "$column_width")) ] ; then
		for a in $column_2 ; do
			if [ "$line" ] ; then
				line="${line}$a "
			else
				if [ $(( ${#right} + ${#a} )) -le $(( 80 - "$column_width" )) ] ; then
					right="${right}$a "
				else
					printf '%'$((80 - ${#left} - "$column_width"))'s' | tr " " "$separ"
					echo "$right"
					line="$a "
				fi
			fi
		done
		long "$line" |sed 's/:[[:space:]]*$//'
	else  
		if [ ${#left} -gt 0 ] ; then
			printf '%'$((80 - ${#left} - "$column_width" ))'s' | tr " " "$separ"
		else
			printf '%'$((80 - ${#left} - "$column_width" ))'s'
		fi
		echo -en " "
		echo "$column_2" |sed 's/:[[:space:]]*$//'
	fi
else
	column_2="$2"; column_1="$1"
	for a in $column_1 ; do
		if [ $(( ${#str} + ${#a} )) -le "$column_width" ] ; then
			str="${str}$a "
		else
			echo -e "$str"
			str="$a "
		fi
	done
	echo -ne "$str"
	if [ "$color" == "$def_color" ] ; then
		= $mark_color
		color_changed=yes
	fi

	if [ ${#column_2} -gt 80  ] ; then
		echo ''
		long "$column_2"
	elif [ ${#column_2} -gt $((80 - "$column_width")) ] ; then
		echo ''
		printf '%'$((79 - ${#column_2}))'s'
		echo -e "$column_2"
	else
		printf '%'$(("$column_width" - ${#str}))'s' | tr " " "$separ"
		echo -en "  "
		echo "$column_2"
	fi
	[ "$color_changed" ] && = default
fi
}

long () {
	local lenstr=0 lenstr_=0 str=''
	set -o noglob
	for a in $@ ; do
	lenstr_=$(( ${#str} + ${#a} ))
	if [ $lenstr_ -lt "80" ] ; then
		str="${str}$a "
	else
		[ -z "$str" ] || echo $(echo "${str}" | sed 's/.\{80\}/&\n/g')'\'
		str="$a "
	fi
	done
	echo "$str" | sed 's/.\{80\}/&\n/g' 
}

++() {
	printf '%'$(( (80 - ${#1}) / 2  ))'s'
	echo -e "$1"
}

+ () {
	local lenstr=0 lenstr_=0 str=''
	set -o noglob
	for a in $@ ; do
	lenstr_=$(( ${#str} + ${#a} ))
	if [ $lenstr_ -lt 60 ] ; then
		str="${str} $a"
	else
		++ "$str"
		str=$a
	fi
	done
	++ "$str"
}

find_help(){
	local pattern directsearch a block
	if [ "$1" == '%' ] ; then
		shift
		HIDE=yes
	elif [ "$1" == '!' ] ; then
		shift
		USELESS=no
	elif [ "$1" == '+' ] ; then
		INTERACTIVE='yes'
		shift
	fi
	file="$STARTFILE"
	if ! [ "$1" ] ; then
		file=${HELPDIR}/$STARTFILE
		return 0
	fi
	pattern="${STARTFILE}$(echo $@ |sed -e 's:\ :.:g' -e 's/^/.*/')"
	directsearch=$(ls -1 $HELPDIR  |grep  "$pattern")
	if [ "$(echo $directsearch |wc -w)" -ne 1 ] ;then
		n=2
		[ "$HIDE" ] || echo -n "$STARTFILE"
		for a in $@ ; do
			unset block
			block=$(ls -1 $HELPDIR |grep $(basename $file) |awk -F. '{print $'$n'}' |$GREP $a |sort |uniq)
			if [ $(echo $block |wc -w) -eq 1 ] ; then
					file=${file}.$block
					echo -n " -> $block"
			elif [ $(echo $block |wc -w) -eq 0 ] ; then
				echo -e "\n\"$a\" $MSG02" >&2
				return 1
			else
				echo -e "\n\"$a\" - ${MSG01}:\n$block" >&2
				return 1
			fi
			n=$(( $n + 1))
		done
		echo ''
	else
		file=$directsearch
		[ "$HIDE" ] || echo $file |sed 's/\./ -> /g'
	fi
	file=${HELPDIR}/$file
}


search() {
	= brown
	+ ${MSG05}:
	= default
	grep -rw  "$1" "$HELPDIR" |sed -e 's#'"${HELPDIR}/"'##' 	-e 's/:/ /' \
	| cut -f1 -d ' ' |sort -u |sed 's/\./ /g' 
}

[ "$1" != '%' ] && echo -e \
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ $(date +%d.%m.%y) ■■■■■■■■
if [ "$1" == '-' ] ; then
	shift ; break='yes'
	echo "$@" >&2
	= green
	while read str; do
		echo -e "$str" >&2
	done
	= default
elif [ "$1" == '?' ] ; then
	shift ; break='yes' 
	search "$@"
elif find_help $@ ; then 
	if [ $USELESS != 'yes' ] ;then
		source $file 2>/dev/null | less -FEXI 
	else
		source $file 2>/dev/null
	fi
fi
[ "$1" != '%' ] && echo -e \
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■⌚ ️$(date +%H:%M:%S) ■■■■■■■■
[ $break ] && exit

subpart=$(find $HELPDIR -type f -not -type l |grep -E $(basename $file)'\.[^\.]+*$' |grep -v header |sed 's:'${HELPDIR}/$(basename $file).'::g')
strname="$(echo ${file} |sed -e 's:'${HELPDIR}/$STARTFILE'::' -e 's/^\.//')"
if [ -n "$subpart" ] ; then
	if [ -n "$strname" ] ; then 
		echo -e "$MSG04 \""$strname"\":"
	else
		echo -e "${MSG04}:"
	fi
fi
if [ "$INTERACTIVE" != 'yes' ] ; then
	long $subpart
else
	mapfile -t subparts_array <<< "$subpart"
	if [ -n "$subpart" ]  ;then
		column_width=30
		mark_color=default
		def_color=default
		for i in "${!subparts_array[@]}"; do
			if [ "$f" ] ; then
				_ "$(printf "(%2d) %s\n" $((f+1)) "${subparts_array[$f]}")" "$(printf "(%2d) %s\n" $((i+1)) "${subparts_array[$i]}")"
				unset f
			else
				f="$i"
			fi
		done
		if [ "$f" ] ; then
			_ "$(printf "(%2d) %s\n" $((f+1)) "${subparts_array[$f]}")" "$(printf "(%2s) %s\n" 'q' "Quit")"
		else
			printf "(%2s)- %s\n" 'q' "Quit"
		fi
		echo ''
		while true; do
			read -rp "$MSG06 (1-${#subparts_array[@]}): " choice
			[ "$choice" == 'q' -o "$choice" == 'Q' ] && exit 0
			if [[ ! "$choice" =~ ^[0-9]+$ ]]; then
				echo "$MSG07"
				continue
			fi
			if (( choice < 1 || choice > ${#subparts_array[@]} )); then
				echo "$MSG08"
				continue
			fi
			break
		done
		selected="${subparts_array[$((choice-1))]}"
		exec $0 "$1" $strname $selected
	fi
fi
