#!/bin/bash
set -e
#set -x

x=$(dirname "$0")
cd "$x"

JAR="$HOME/.m2/repository/org/gvsig/org.gvsig.crs.catalog.lib.milnga/3.0.0-SNAPSHOT/org.gvsig.crs.catalog.lib.milnga-3.0.0-SNAPSHOT.jar"

DATADIR=$(realpath "../data")
EPSGDIR="$DATADIR/authorities/epsg"

LOGFILE="$EPSGDIR/transformation.log"
CSVFILE="$EPSGDIR/transformation.csv"
WKTSDIR="$EPSGDIR/transformation"
HEADER="#Id,Description,Source,Target,type,method"
OPERATION="--transformation"

if [[ "$1" != "" ]] ; then
    WKTFILE=$(realpath "$1")
    java -cp "$JAR" org.gvsig.crs.catalog.cmdutils.ExtractValues $OPERATION "$WKTFILE"
    exit $?
fi

rm -f "$LOGFILE"
cd "$WKTSDIR"
declare -i errores=0
echo "$HEADER" >"$CSVFILE"
for f in *.wkt 
do 
    echo "$f"
    echo "$f" >>"$LOGFILE"
    WKTFILE=$(realpath $f)
    err=0
    line=$(java -cp "$JAR" org.gvsig.crs.catalog.cmdutils.ExtractValues $OPERATION "$WKTFILE" 2>>"$LOGFILE") || err=$?
    if [[ $err == 0 ]] ; then
      if [[ "$line" != "" -a "$line" != "\n" ]] ; then
          echo "$line" >>"$CSVFILE"
      fi
    else
      echo "skip file ($err)"
      errores=$(($errores + 1))
    fi
done
if [[ $errores != 0 ]] ; then
	echo "Se han producido $errores errores, consulte el archivo log $(basename $LOGFILE)" >&2
fi

