#!/bin/sh
#
# vym2txt.sh
#
VERSION="0.11"
# Date: 20040417
# Author: Clemens Kraus (http://www.clemens-kraus.de)
#
#echo $@


unpacker()
# Unpack vym-file, only if it is one
{
  echo $VYMFILE_EXT | grep -F ".vym" 1>/dev/null

  if [ $? = 0 ] ; then
	  echo ">> Unpacking files ..."
	  unzip $VYMFILE_EXT -d $VYMFILE_PATH 1>/dev/null
	  if [ $? -gt 0 ] ; then
		echo ">>> Error in unzip! Aborting."
	  	exit 4
	  fi
  fi
}


txt2xml()
# change all txt-files into xml-format
{
  for i in `ls $VYMFILE-note-*.txt 2>/dev/null`
  do
    # Check whether already modified
	grep "<note>" $i 1>/dev/null
	
	if [ $? -gt 0 ] ; then
	  echo ">> Modifying: "$i
	  # Each line gets an additional <line>-tag, because of the indents!
	  sed -e 's,^,<line><![CDATA[,g' -e 's,$,]]>\&#xA;</line>,g' $i > $i"_tmp"
	  
	  #cp $i $i"_tmp"
	  echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" > $i
	  echo "<note>" >> $i
	  #echo "<![CDATA[" >> $i
	  cat $i"_tmp" >> $i
	  #echo "]]>" >> $i
	  echo "</note>" >> $i
  
	  rm $i"_tmp"
	fi
  done
}


transform()
{
  echo ">> Starting XSLT transformation ..."
# sabcmd vym2html.xsl $VYMFILE".xml"  \$filenamep=$VYMFILE \$wikistylep=$WIKISTYLEP \$genimagep=$GENIMAGEP \$stylesheetp=$STYLESHEETP > $VYMFILE".html"
  xsltproc -o $VYMFILE".txt" --stringparam filenamep `pwd`/"$VYMFILE" `dirname $STYLESHEETP`/vym2txt.xsl  $VYMFILE".xml"
  
  if [ $? -gt 0 ] ; then
	  echo ">>> Error in xsltproc! Aborting."
	  exit 3
  fi
}


remove_files()
# remove all temporary unpacked vym-files
{
  echo $VYMFILE_EXT | grep -F ".vym" 1>/dev/null
	
  if [ $? = 0 ] ; then
	echo ">> Removing temporary files ..."
	for i in `ls $VYMFILE-note-*.txt 2>/dev/null`
	do
	  rm $i
	done
  
	for i in `ls $VYMFILE-image-*.* 2>/dev/null`
	do
	  rm $i
	done
  
	rm $VYMFILE".xml" 2>/dev/null
  fi
}

# -------------------- Parameter check -----------------------
STYLESHEETP=""

USAGE="USAGE:\t`basename $0`  vymfile.[vym|xml]  -sp=\077  [Options]\n"
USAGE=$USAGE"\t-sp=\077: absolute stylesheet path (including name of stylesheet)\n"
USAGE=$USAGE"Output:\tvymfile.txt\n\n"
USAGE=$USAGE"Options:\n"
USAGE=$USAGE"-v: prints the version of vym2txt\n"

if [ "$1" = '-v' ]; then
	  echo "vym2txt Version: "$VERSION
	  exit 0
fi
if [ $# -lt 1 -o $# -gt 2 -o "$1" = '-help' ]; then 
	echo -e $USAGE
	exit 1
else
	VYMFILE_EXT=$1
	VYMFILE=`echo $VYMFILE_EXT | cut -d. -f1`
	VYMFILE_PATH=`dirname $VYMFILE_EXT`
fi

for arg in $2
do
  if [ ${arg:0:3} = '-sp' ]; then		# take first 3 chars
	  STYLESHEETP=`echo $arg | cut -d= -f2`
  elif [ "$arg" = '-help' ]; then
	echo -e $USAGE
	exit 1
  else
	echo -e $USAGE
	exit 1
  fi
done


# ---------------------- Los geht's --------------------------
echo ">> Processing file '$VYMFILE_EXT' ..."

# Unpack vym-file
unpacker

txt2xml

# Transform
transform

# clean up
remove_files

echo ">> Ready!"
echo ">> ---------------------"

exit 0


