#!/bin/bash

EXTS="png jpg eps pdf"

TEMP=/tmp/$(basename $0 .sh).temp
[ -d $TEMP ] || mkdir -p $TEMP

ACROREAD=$(which acroread 2>/dev/null)
DVIPDFMX=$(which dvipdfmx 2>/dev/null)
GS=$(which gs 2>/dev/null)

[ -z "$ACROREAD" ] && echo "please run apt-get install install-assist-AdobeReader_jpn" && exit 1
[ -z "$DVIPDFMX" ] && echo "please run apt-get install dvipdfmx" && exit 1
[ -z "$GS" ] && echo "please run apt-get install ghostscript" && exit 1

EPS=/usr/share/ghostscript/$(gs --version)/examples/tiger.eps

GS="$GS -dSAFER -dBATCH -dNOPAUSE" 

## genpdf [ext]
genpdf(){
    local ext=$1
    local srcname=$(basename $EPS .eps)
    local target=${srcname}.${ext}

    local gs_dev=
    case $ext in
	eps)
	    ;;
	png)
	    gs_dev=pngalpha
	    ;;
	jpg)
	    gs_dev=jpegcmyk
	    ;;
	pdf)
	    gs_dev=pdfwrite
	    ;;
	*)
	    echo "E: unsupported extension: $ext"
	    exit 1
	    ;;
    esac

    ## convert a target media file from $EPS
    if [ ! -z $gs_dev ]; then
	rm -f ${target}
	$GS -sDEVICE=$gs_dev -sOutputFile=${target} $EPS
	[ ! -f ${target} ] && exit 1
	ebb -b ${target}
    else
	target=$EPS
    fi

    ## generate embedded $target pdf
    cat<<EOF > ${srcname}.tex
\documentclass{jarticle}
\usepackage[dvipdfmx]{graphicx}
\begin{document}
\includegraphics{${target}}
\end{document}
EOF
    platex ${srcname}
    dvipdfmx -o ${srcname}-${ext}.pdf ${srcname}
}

cd $TEMP
rm -f *
for i in $EXTS; do genpdf $i; done
$ACROREAD *.pdf
cd -

exit

### end of file
