#!/bin/bash
#
# ::do_not_edit::
#
# ::copy::
# ::maintainer::
#
CMD=$(basename $0)
CMDVER="2.4"
CMDSTR="$CMD v$CMDVER (2022-04-18)"

set -e -u


usage()
{
	[ $# != 0 ] && echo -e "\n$@" >&2

	echo "
== $CMDSTR = libreoffice launcher with history search ==

usage:	$CMD [options] [libreoffice_parms] file
	$CMD [options] libreoffice_parms

options:
 -D|--debug	activate script debug
 -h|--help	show help
 -f|--first	use first file from history, if more than one file
 		is found
 -n|--dry-run	don't run anything (implies --debug)

* run	$OFFICE_PATH --help
	for complete libreoffice options usage

* the application command is 'libreoffice', usually installed in /usr/bin as
  symlink (see /etc/alternatives); set environment \$OFFICE_PATH to override

* actual libreoffice version:" >&2

	libreoffice -h | grep "^LibreOffice"
	exit 1
}


run_soffice()
{
	local file="$1" ; shift
	local dir=

	# absolutize filename
	case "$file" in
	  */*)	dir=$(dirname "$file")
	  	[ -d "$dir" ] || {
			echo "dir '$dir' not exists" >&2
			return 1
		}
		dir=$( (cd "$dir"; pwd) )
	  	file=$(basename "$file")
		;;
	  *)	dir=$(pwd)
	 	;;
	esac

	$DEBUG && echo "D> try dir='$dir' 'file=$file'" >&2

	file="$dir/$file"

	grep -v " $file$" $histfile | sponge $histfile

	[ -f "$file" ] || return 1
	echo "$(date '+%Y%m%d-%H%M%S') $file" >>$histfile

	exec_soffice "$@" "$file"
}



exec_soffice()
{
	# TODO dirty hack, please find another way to fix this
	[ "$LANG" = "" -o "$LANG" = "C" ] && export LANG="it_IT.UTF-8"
	umask 002
	$DEBUG && {
		echo "(dry run) '$OFFICE_PATH' $*"
		return 0
	}
	"$OFFICE_PATH" "$@" 2>"$HOME/.xsession-errors" &
}

# (MAIN)

file=
f_first=false
f_exec=true
declare -A args
nargs=0

DEBUG=${DEBUG:-false}
OFFICE_PATH=${OFFICE_PATH:-libreoffice}
histfile="$HOME/.${CMD}_history"
searchpath="/opt/libreoffice*"

while [ $# != 0 ]
do
  case $1 in
    -D|--debug)		DEBUG=true ;;
    -n|--dry-run)	f_exec=false ; DEBUG=true ;;
    -h|--help)		usage ;;
    -f|--first)		f_first=true ;;
    -*)			let nargs="$nargs + 1"; args[$nargs]=$1 ;;
    *)			[ "X$file" != "X" ] && usage "error: multiple filenames not allowed"
    			file=$1
			;;
  esac
  shift
done

[ "X$file" = "X" -a "$nargs" = 0 ] && \
	usage "error: no filename provided, you need at least one libreoffice argument"

[ -f $histfile ] || {
	:>$histfile
}

# no file, launch office itself (needs at least one office arg)
#
# ps: note the convoluted ${args...} expression instead of simply ${args[@]}, due a bug
#     affecting bash prior to 4.4, see:
#     https://stackoverflow.com/questions/7577052/bash-empty-array-expansion-with-set-u
#
[ "X$file" = "X" ] && exec_soffice ${args[@]+"${args[@]}"}


# 2015.07.03
# patch: removes wrong entries (missing absolute path) left by
# old version of this command
#
grep -v " [^/]" $histfile | sponge $histfile

# first try, direct
#
run_soffice "$file" ${args[@]+"${args[@]}"} && exit 0


# ok, smart search the file ...

for search in "$file" "$file.*" ".*$file" ".*$file.*"
do
	$DEBUG && echo "D> search '$search' ..." >&2
	found=$(grep " $search$" $histfile || :)
	[ "X$found" != "X" ] && break
done
$DEBUG && echo "D> found: '$found'" >&2

[ "X$found" = "X" ] && {
	echo "file '$file' not found in history" >&2
	exit 1
}

# multiple files from history and 'use first' option?
#
[ $(echo "$found" | wc -l) != 1 ] && {
	$f_first && {
		found=$(echo "$found" | sort -r | head -1)
	}
}

[ $(echo "$found" | wc -l) = 1 ] && {
	file=$(echo "$found" | sed -e 's/^[^ ]* //')
	echo -e "\n$found\n"
	sleep 1
	run_soffice "$file" ${args[@]+"${args[@]}"} || {
		grep -v " $file$" $histfile | sponge $histfile
		echo "file '$file' not exists, removed from history"
		exit 1
	}
	exit 0
}

# multiple files from history

echo -e "\nmultiple files found, please restrict your choiche:\n"
if [ -z ${PRJ:-} ]
then
	echo "$found" | sort -r
else
	echo "$found" | sort -r | sed -e "s{$PRJ{\$PRJ{g"
fi
echo

exit 0
