#! /bin/bash

if [ $# -lt 3 ]; then
	echo "Usage: $0 <inputmap> <outputprefix> <attrname>" >&2
	exit 1;
fi

inputmap="$1"
outputprefix="$2"
attr="$3"

basedir="$outputprefix"

[ -d "$basedir" ] || mkdir -p "$basedir"

thedate=`date +%Y%m%d`

outputdir="$outputprefix-$thedate"

dsn="$basedir/$outputdir"

rm -Rf "$dsn"

v.out.ogr -c input="$inputmap" type=area dsn="$dsn" olayer=rawsource

OGR2OGR="ogr2ogr -t_srs wgs84 -overwrite"
OGR2PATHS="$dsn $dsn rawsource"

$OGR2OGR -nln v0_town -where "$attr=111" $OGR2PATHS
$OGR2OGR -nln v0_urban -where "$attr=112 or ($attr>=141 and $attr<=142)" $OGR2PATHS
$OGR2OGR -nln v0_industrial -where "($attr>=121 and $attr<=124) or ($attr>=131 and $attr<=133)" $OGR2PATHS
$OGR2OGR -nln v0_drycroppasturecover -where "$attr=211 or ($attr>=221 and $attr<=223)" $OGR2PATHS
$OGR2OGR -nln v0_irrcroppasturecover -where "$attr=212 or $attr=213" $OGR2PATHS
$OGR2OGR -nln v0_cropgrasscover -where "$attr=231" $OGR2PATHS
$OGR2OGR -nln v0_mixedcroppasturecover -where "$attr>=241 and $attr<=244" $OGR2PATHS
$OGR2OGR -nln v0_deciduousbroadcover -where "$attr=311" $OGR2PATHS
$OGR2OGR -nln v0_evergreenbroadcover -where "$attr=312" $OGR2PATHS
$OGR2OGR -nln v0_mixedforestcover -where "$attr=313" $OGR2PATHS
$OGR2OGR -nln v0_scrubcover -where "$attr>=321 and $attr<=324" $OGR2PATHS
$OGR2OGR -nln v0_sand -where "$attr=331" $OGR2PATHS
$OGR2OGR -nln v0_barrencover -where "$attr=332" $OGR2PATHS
$OGR2OGR -nln v0_bog -where "$attr=333 or $attr=334" $OGR2PATHS
$OGR2OGR -nln v0_glacier -where "$attr=335" $OGR2PATHS
$OGR2OGR -nln v0_marsh -where "$attr=411 or ($attr>=421 and $attr<=423)" $OGR2PATHS
$OGR2OGR -nln v0_lake -where "$attr>=511 and $attr<=522" $OGR2PATHS

tar czvf "$basedir/$outputdir.tar.gz" -C "$basedir" "$outputdir"

