#! /bin/bash -

# mswd2pdf
#
# H.A.Trujillo,    21 Feb 2019
# Version:	   3.0
# Last Change:     23 Feb 2019
#
#	Allows for automated conversion of MSWD files to pdf files.
#


fname=${0##*/}

function help {
    gr=`tput setaf 2`	# green
    pl=`tput sgr0`	# plain

    cat <<- EOT

	  ${gr}${fname}${pl}
	        Converts a MSWD file into a .pdf file
	
	        By default, the new file is left in the same directory as the
	        original file

	     Usage:
	        $fname [-f] [-o outfile] infile

	     Options:
	        -f  force overwriting of output file
	        -o  specify output file
	        -h  print this message

EOT
}

# --- Start Here ---

while [ $1 ] ; do
    case $1 in
	-h) help ; exit
	    ;;
	-o) outpath="$2" ; shift
	    ;;
	-f) forcewrite=1
	    ;;
	 *)  break
	    ;;
    esac
    shift
done

if [ $# != 1 ] ; then
    echo "    wrong number of arguments.  See $fname -h"
    exit 1
fi

#	OS 10.13 sandboxing requires that MSWD read and write files here:
tmpdir=$HOME/Library/Containers/com.microsoft.Word/Data/Documents

inpath=$1 			# /a/b/c.docx
infile=$(basename $inpath)	# c.docx

: ${outpath:=$inpath}		# /a/b/c.docx
outdir=$(dirname $outpath)	# /a/b	
outfile=$(basename $outpath)
outfile=${outfile%.*}.pdf	# c.pdf

if [ ! -e "$inpath" ] ; then
    echo   "     Oops -- no such file: $infile "
    exit 1
fi


if [ -e ${outdir}/${outfile}  -a  ! "$forcewrite" ]  ; then 
    printf "    Overwrite $outfile ?   [yN]  "
    read
    if [ ! "$REPLY" == "y" ] ; then exit 1 ; fi
fi


#	Sandboxing requires a hard-link, rather than a sym-link.  Will cause
#	problems if run across volumes.
ln $inpath ${tmpdir}/${infile}

if [ $(ps ax | grep "MacOS/Microsoft Word" | grep -v grep | wc -l) != 0 ] 
    then  WordIsRunning=1 ; fi


{ osascript  << EOT 
    tell application "Microsoft Word"
	launch
	open "$tmpdir/$infile"
	tell active document
	    save as it file name "$tmpdir/$outfile" file format format PDF
	    close saving no
	end tell
    end tell
EOT
} 2>&1 | grep -v "ApplePersistence=NO"


mv ${tmpdir}/${outfile} ${outdir}/
rm ${tmpdir}/${infile}

if [ ! $WordIsRunning ] ; then 
    PID=$(ps ax | grep "MacOS/Microsoft Word" | grep -v grep | cut -c1-6)
    kill -3 $PID
fi

exit

# ------------------------------
#
# v1		  AppleScript for OS 10.6  / Word 2008 ?
# v2	2013	  Applescript for OX 10.8  / Word 2011
# v3.0	22feb19	  bash script for OS 10.13 / Word 2016
