#!/bin/sh

XDVI=/etc/texmf/vfontmap
cfg_default=/etc/texmf/dvipsj/config.ps
#cfg_old=/etc/texmf/dvipsj/config.ps

function set_up ()
{
cfg_var="$1"
     if [ -f ${cfg_var} ] ; then
    	if ! grep -q "%-- morisawa begin" ${cfg_var}; then
	echo -n "modifying ${cfg_var} ..."
    	sed -e '/^p psfonts.map/a\
%-- morisawa begin\
p +morisawa.map\
%-- morisawa end' < ${cfg_var} > ${cfg_var}_$$ && \
    	mv -f ${cfg_var}_$$ ${cfg_var}
	echo "done"
    	fi
      else
	echo "You should install dvipsk-ja first then do \"morisawa-config add\" "
     fi
    return 0
}

function set_up_other ()
{
cfg_var="$1"
     if [ -f ${cfg_var} ] ; then
    	if ! grep -q "%-- morisawa begin" ${cfg_var}; then
	echo -n "modifying ${cfg_var} ..."
    	sed -e '$a\
%-- morisawa begin\
p +morisawa.map\
%-- morisawa end' < ${cfg_var} > ${cfg_var}_$$ && \
    	mv -f ${cfg_var}_$$ ${cfg_var}
	echo "done"
    	fi
      else
	echo "You should install ${cfg_var} first."
      fi
    return 0
}

function clean_up ()
{
cnf="$1"
      if [ -f ${cnf} ] ; then
      echo -n "removing settings of ${cnf} ..."
      sed -e '/%-- morisawa begin/,/%-- morisawa end/d' < ${cnf} > \
      ${cnf}_$$ && mv -f ${cnf}_$$ ${cnf}
      echo "done"
      fi
    return 0
}

function set_xdvi ()
{
  if [ -f ${XDVI} ] ; then
   if ! grep -q "##-- morisawa begin" ${XDVI}; then
   echo -n "modifying vfontmap ..."
   sed -e '$a\
##-- morisawa begin\
ryumin-l	min\
gtbbb-m		goth\
ryumin-l-v	min\
gtbbb-m-v	goth\
futomin-b	vfhminb\
futogo-b	vfkgothb\
jun101-l	vfmgoth\
futomin-b-v	vfhminb\
futogo-b-v	vfkgothb\
jun101-l-v	vfmgoth\
##-- morisawa end'\
< ${XDVI} > ${XDVI}_$$ && mv ${XDVI}_$$ ${XDVI}
   echo "done"
   fi
  else
  echo "It seems there is no xdvik-ja installed?"
#  exit 1
  fi
  return 0
}

function rm_xdvi ()
{
   if [ -f ${XDVI} ] ; then
   echo -n "removing settings of ${XDVI} ..."
   sed -e '/##-- morisawa begin/,/##-- morisawa end/d' < ${XDVI} > \
   ${XDVI}_$$ && mv -f ${XDVI}_$$ ${XDVI}
   echo "done"
   fi
   return 0
}

if [ $# -eq 1 ] ; then
cfg=${cfg_default}
   if [ "$1" = "add" ] ; then
       set_up $cfg
   elif [ "$1" = "remove" -o "$1" = "rem" ] ; then
       clean_up ${cfg}
   elif [ "$1" = "xdvi" ] ; then
       set_xdvi
   elif [ "$1" = "remxdvi" ] ; then
       rm_xdvi
   else
      echo "$0 is called with wrong options"
   fi
elif [ $# -eq 2 ] ; then
#cfg=/etc/texmf/dvipsj/"$2"
cfg=/etc/texmf/dvipsj/"$2"
   if [ "$1" = "add" ] ; then
       set_up_other ${cfg}
   elif [ "$1" = "remove" -o "$1" = "rem" ] ; then
       clean_up ${cfg}
   else
      echo "$0 is called with wrong options"
   fi
else
echo "$0 is called with wrong options"
fi
