#!/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

# add $PWD into $PATH for test runs of termhelper from local directory
. termhelper-functions || { echo "termhelper-functions not found!" && exit 1 ;}
_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=60	    	# 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")"

= () { 
	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 "$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
	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 -r  "$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=$(ls -1 $HELPDIR |grep -E $(basename $file)'\.[^\.]+*$' |sed 's/'$(basename $file).'//g')
if [ -n "$subpart" ]  ;then
			echo -e "$MSG04 \"$(echo ${file} |sed -e 's:'${HELPDIR}/$STARTFILE'::' -e 's/^\.//')\":"
			long $subpart
			echo ''
fi

