#!/bin/sh

# Copyright (C) 2018-2020 Simon Spöhel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

set -e

ZIP="${1}"

DIRECTORY="$(dirname ${ZIP} | cut -d/ -f 2-)"
FILE="$(basename ${ZIP} .zip)"

cd "${BASE_DIRECTORY}"

if [ ! -f "GeoTIFF/${DIRECTORY}/${FILE}.tif.sha512" ]
then
	echo -n "Creating GeoTIFF for ${FILE} "

	mkdir -p "GeoTIFF/${DIRECTORY}"
	cd "GeoTIFF/${DIRECTORY}"

	rm -f "${FILE}.tif"

	gdal_translate					\
		-co COMPRESS=DEFLATE			\
		-co PREDICTOR=2				\
		"../../../VRT/${DIRECTORY}/${FILE}.vrt"	\
	${FILE}.tif

	# Keeping old syntax for reference.
	#gdalwarp					\
	#	-tr 10 10				\
	#	-multi					\
	#	-wo NUM_THREADS=val/ALL_CPUS		\
	#	-wm 2000				\
	#	-co COMPRESS=DEFLATE			\
	#	-co PREDICTOR=2				\
	#	-wm GTIFF_VIRTUAL_MEM_IO=IF_ENOUGH_RAM	\
	#	-wm GTIFF_DIRECT_IO=YES			\
	#	../VRT/${DIRECTORY}/${FILE}.vrt		\
	#${FILE}.tif

	sha512sum "${FILE}.tif" > "${FILE}.tif.sha512"

	cd "${BASE_DIRECTORY}"
fi

if [ ! -f "GeoTIFF/${DIRECTORY}/${FILE}.qml" ]
then
	echo -n "Creating QGIS layer style file (qml) for ${FILE} "

cat > "GeoTIFF/${DIRECTORY}/${FILE}.qml" << EOF
<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>
<qgis version="2.18.9" minimumScale="inf" maximumScale="1e+08" hasScaleBasedVisibilityFlag="0">
  <pipe>
    <rasterrenderer opacity="1" alphaBand="0" blueBand="2" greenBand="3" type="multibandcolor" redBand="4">
      <rasterTransparency/>
      <redContrastEnhancement>
        <minValue>0</minValue>
        <maxValue>2000</maxValue>
        <algorithm>StretchToMinimumMaximum</algorithm>
      </redContrastEnhancement>
      <greenContrastEnhancement>
        <minValue>0</minValue>
        <maxValue>2000</maxValue>
        <algorithm>StretchToMinimumMaximum</algorithm>
      </greenContrastEnhancement>
      <blueContrastEnhancement>
        <minValue>0</minValue>
        <maxValue>2000</maxValue>
        <algorithm>StretchToMinimumMaximum</algorithm>
      </blueContrastEnhancement>
    </rasterrenderer>
    <brightnesscontrast brightness="0" contrast="0"/>
    <huesaturation colorizeGreen="128" colorizeOn="0" colorizeRed="255" colorizeBlue="128" grayscaleMode="0" saturation="0" colorizeStrength="100"/>
    <rasterresampler maxOversampling="2"/>
  </pipe>
  <blendMode>0</blendMode>
</qgis>
EOF

	echo " done."
fi

cd "${OLDPWD}"
