#!/bin/sh

# WWS command suite
#
## generate PNG images
## pretty print SVG files

if [ $# -ne 1 ]; then
  cat <<END
Usage: `basename $0` <png|readmes>
  png: generate PNG versions of symbols
  readmes: generate README.md files for symbol directory indexes

END
  exit 1
fi

COUNTER=0
THISDIR=`dirname $0`
ROOTDIR=$THISDIR/../symbols
PNG_DIR=$ROOTDIR/png
TMP_DIR=$ROOTDIR/tmp
SVG_FILES=`find $ROOTDIR -type f -name "*.svg"`

case $1 in
    "png" )
    echo "Generating PNG images"
    if [ ! `which inkscape` >/dev/null ]; then
        echo "inkscape is not installed on this system.  Install with \`sudo apt-get install inkscape\`"
        exit 2
    fi    
    if [ ! -d "$PNG_DIR" ]; then
        mkdir $PNG_DIR
    fi
    for svg in $SVG_FILES
    do
      BASENAME=`basename $svg .svg`
      inkscape --export-type=png --export-filename=$PNG_DIR/$BASENAME.png $svg -l
      status=$?
      if [ $status -ne 0 ]; then
          COUNTER=$((COUNTER+1))
      fi
    done
    exit $COUNTER
    ;;
esac

case $1 in
    "readmes" )
    echo "Generating README.md previews of symbol directories"
    SVG_DIRS=`find $ROOTDIR -type d`
    ROOT_SYMBOLS_README=./scripts/../symbols/README.md
    for svg_dir in $SVG_DIRS
    do
      echo "Creating $README"
      DIRECTORY_NAME=`basename $svg_dir`
      README=$svg_dir/README.md
      if [ $README = $ROOT_SYMBOLS_README ]; then
          continue
      fi
      echo "# $DIRECTORY_NAME symbols\n" > $README
      echo "Automated list of symbols in the $DIRECTORY_NAME directory\n" >> $README 

      echo "|     | Symbols |" >> $README
      echo "| --- |:-------:|" >> $README

      svg_dir_files=`find $svg_dir -type f -name "*.svg"|sort`
      for svg_dir_file in $svg_dir_files
      do
        TITLE=`cat $svg_dir_file |grep -Po "<svg:title>(.*)</svg:title>"|sed -e 's#<svg:title>##' -e 's#</svg:title>##'`
        SVG_DIR_FILE2=`echo $svg_dir_file|sed 's#./scripts/../##'`
        SVG_FILENAME=`basename $svg_dir_file`
        SVG_FILENAME2=`basename $svg_dir_file .svg`
        echo "| **Filename/symbol** | $SVG_FILENAME ![$SVG_FILENAME2](https://cdn.rawgit.com/OGCMetOceanDWG/WorldWeatherSymbols/master/$SVG_DIR_FILE2)|" >> $README
        echo "| **Description** | $TITLE |" >> $README
      done
      echo "\n*This \`README.md\` automatically generated by [www_manage.sh](https://github.com/OGCMetOceanDWG/WorldWeatherSymbols/blob/master/scripts/wws_manage.sh)*" >> $README
    done
esac
