#!/bin/bash
# Copyright (c) 2011, Brian Case
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

#usage super.bash myindir/ myoutdir/

indir="$1"
outdir="$2"

##### make temp dir #####

tmpdir=$(mktemp -d -p "/tmp" "superXXXXXXXXXX")

##### loop over the kmz files #####

for kmz in $(find "$indir" -name "*.kmz")
do
    
    tmpdir=$(mktemp -d -p "/tmp" "superXXXXXXXXXX")

    ##### unzip the doc.kml from the kmz #####

    unzip "$kmz" "doc.kml" -d "$tmpdir"

    
    ##### loop over each image listed as draworder 7 in the doc.kml #####

    while read f n s e w
    do
    
        ##### unzip the image #####

        unzip "$kmz" "$f" -d "$tmpdir"

        ##### vuild a vrt for the image #####

        gdal_translate -a_srs EPSG:4326 \
                       -a_ullr $w $n $e $s \
                       -of VRT -mask none \
                       "${tmpdir}/${f}" \
                       "${tmpdir}/${f}.vrt"

    done < <( grep 'drawOrder>7' -A9 doc.kml |\
               tr "\r" " "|\
               tr "\n" " " |\
               (sed 's/--/\n/g'; echo) |\
               sed 's:.*<href>\(.*\)</href>.*<north>\(.*\)</north>.*<south>\(.*\)</south>.*<east>\(.*\)</east>.*<west>\(.*\)</west>.*:\1 \2 \3 \4 \5:'
          )
 
    gdalwarp ${tmpdir}/*.vrt "${outdir}/${kmz##*/}.tif"

    rm -r "$tmpdir"

done



