#!/bin/bash

define() { IFS='\n' read -r -d '' ${1} || true ; }

myname="$(basename $0)"

define pod <<"=cut"

=head1 NAME

    xlate - Front-end CLI tool for App::Greple::xlate module

=head1 SYNOPSIS

    xlate [ options ] file [ greple options ]
	-h   help
	-d   debug
	-a   use API
	-c   just check translation area
	-r   refresh cache
	-s   silent mode
	-p#  pattern to determine translation area
	-w#  wrap line by # width
	-x#  set xlate format (xtxt, cm, ifdef)
	-f#  from lang (ignored)
	-t#  to lang
	-m#  max length per API call

	-D   run on the Docker container
	-M   run semi-automatic make

    Control Files:
	*.LANG    translation languates
	*.FORMAT  translation foramt (xtxt, cm, ifdef)

=head1 VERSION

    Version 0.15

=cut

while getopts :${EXOPT:=dI:D} OPT
do
    case $OPT in
	d)
	    debug=yes ; set -x ;;
	I)
	    container="$OPTARG" ;;
	D)
	    if [ "$XLATE_RUNNING_DOCKER" == "" ]
	    then
		ip=$(ifconfig | awk '/inet /{print $2}' | tail -1)
		if [[ "$pod" =~ Version\ ([0-9]+.[0-9_]+) ]]
		then
		    version=${BASH_REMATCH[1]}
		fi
		exec docker run --rm -it \
		     --hostname xlate \
		     -v $(pwd):/app \
		     -e XLATE_RUNNING_DOCKER=1 \
		     -e DEEPL_AUTH_KEY=$DEEPL_AUTH_KEY \
		     -e DISPLAY="$ip:0" \
		     ${container:-tecolicom/xlate${version:+:$version}} \
		     xlate ${1+"$@"}
		exit;
	    fi
	    ;;
    esac
done
OPTIND=1

while getopts "$EXOPT"'hdacrsMnp:w:x:f:t:m:' OPT
do
    case $OPT in
	[$EXOPT]) ;;
	d)     debug=yes ; set -x ;;
	a)   use_api=yes ;;
	c)     check=yes ;;
	r)   refresh=yes ;;
	s)    silent=yes ;;
	M)  run_make=yes ;;
	n)    dryrun=yes ;;
	p)   pattern="$OPTARG" ;;
	w)      wrap="$OPTARG" ;;
	x)    format="$OPTARG" ;;
	f) from_lang="$OPTARG" ;;
	t)   to_lang="$OPTARG" ;;
	m)       max="$OPTARG" ;;
	h)
	    help="$(sed -r -e 's/^=[a-z]+[0-9]* *//' <<< "$pod")"
	    exec echo "$help"
	    exit
	    ;;
    esac
done	
shift $((OPTIND - 1))

: ${to_lang:=EN-US}
: ${format:=xtxt}

if [[ "$format" =~ ^(.+)-fold$ ]]
then
    format=${BASH_REMATCH[1]}
    : ${wrap:=76}
fi

declare -a module option

module+=(-Mxlate::deepl) 
option+=(--xlate-to="$to_lang" --xlate-format="$format" --xlate-cache=yes)
option+=(--all)

[ "$use_api" == yes ] || use_clipboard=yes
[ "$check"   == yes ] || option+=(--xlate${use_clipboard:+-labor})
[ "$wrap"    != ""  ] && option+=(--xlate-fold-line --xlate-fold-width=$wrap)
[ "$debug"   == yes ] && option+=(-dmo)
[ "$refresh" == yes ] && option+=(--cache-clear)
[ "$silent"  == yes ] && option+=(--no-xlate-progress)
[ "$pattern" != ""  ] && option+=(--re="$pattern")
[ "$max"     != ""  ] && option+=(--xlate-maxlen="$max")

: run make
if [ "$run_make" == yes ]
then
    mod="App-Greple-xlate"
    share=$(perl -MFile::Share=:all -E "say dist_dir '$mod'")
    declare opt
    for m in $*
    do
	if [ -f "$m" ]
	then
	    # GNU Make behaves differently in different versions with
	    # respect to double-quoted strings and spaces within them.
	    file="${file:+$file|||}$m"
	else
	    opt+=("$m")
	fi
    done
    unset MAKELEVEL
    exec make -f $share/XLATE.mk \
	 ${dryrun:+-n} \
	 XLATE_LANG=$to_lang \
	 XLATE_DEBUG=$debug \
	 XLATE_MAXLEN=$max \
	 XLATE_USEAPI=$use_api \
	 ${file:+XLATE_FILES=\"$file\"} \
	 ${opt[@]}
    exit 1
fi

declare -a area
case $1 in
    *.txt)
	area=(--re '^(.+\n)+')
	;;
    *.md)
	area=(--re '(?x) ^[-+#].*\n | ^(.+\n)+ ')
	option+=(--exclude '^([ \t]+.*\n)+')
	;;
    *.pm|*.pod)
	module+=(-Mperl)
	option+=(--pod)
	option+=(--exclude '^=head\d +(VERSION|AUTHOR|LICENSE).*\n(?s:.*?)(?=^=|\z)')
	area=(--re '^(\w.+\n)+')
	;;
    *.docx|*.pptx)
	module+=(-Mmsdoc)
	option+=(--exclude '^\[.*\b(docx|pptx)\b.*\]\n')
	area=(--re '^.+\n')
	;;
    *)
	area=(--re '^.+\n')
	;;
esac

if [ "$pattern" != "" ]
then
    option+=(--re "$pattern")
else
    option+=("${area[@]}")
fi

greple "${module[@]}" "${option[@]}" ${1+"$@"}
