#!/bin/bash
#
# ::copy::
# ::maintainer::
#
CMD=`basename $0`
history="$HOME/.${CMD}_history"
officepath="/opt/libreoffice5.0/program/soffice"
DEBUG=false

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

	echo "
usage:	$CMD [libreoffice_parms] file
	$CMD libreoffice_parms

use $officepath --help for complete options usage
" >&2
	exit 1
}

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

	# absolutize filename
	case "$file" in
	  */*)	dir=$(dirname "$file"); 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$" $history | sponge $history

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

	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
	$officepath "$@" &
}

# (MAIN)

args=
file=

while [ $# != 0 ]
do
  case $1 in
    -D|--debug)	DEBUG=true ;;
    -h|--help)	usage ;;
    -*)		args="$args $1" ;;
    *)		[ "X$file" != "X" ] && usage "error: multiple filenames not allowed"
    		file=$1
		;;
  esac
  shift
done

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


[ -f $history ] || cp /dev/null $history

set -- $args

# no file, launch office itself (needs at least one office arg)
#
[ "X$file" == "X" ] && exec_soffice "$@"


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

# first try, direct
#
run_soffice "$file" "$@" && exit 0


# not found, search in history
#
##for search in "$file" "$file*" "*$file" "*$file*"
##do
	##$DEBUG && echo "D> search '$search' ..." >&2
	##found=`cat $history | while read date file
	##do
		##case $file in
	 		##$search)
				##$DEBUG && echo "D> found $date $file" >&2
				##echo "$date $file" ;;
		##esac
	##done`
	##[ "X$found" != "X" ] && break
##done

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

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

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

echo -e "\nmultiple files found, please restrict your choiche:\n\n$found\n"
exit 0
