#!/bin/bash

shapefile=true

# FUNCTION help_short()
#
# Print short usage information.
function help_short() {
    echo "Usage: $0 [-h|--help] [--no-shapefile]"
}

# FUNCTION help_long()
#
# Print detailed usage information.
function help_long() {
    help_short
    printf "\t--no-shapefile\tDo not download shapefile.\n"
    printf "\t-h,--help\tPrint this help.\n"
}

# FUNCTION error(...)
#
# Print error composed of arguments, then exit.
function error() {
    echo "$0: $*" >> /dev/stderr
    exit 1
}

# FUNCTION error_and_usage(...)
#
# Print error composed of arguments, followed by help, then exit.
function error_and_usage() {
    echo "$0: $*" >> /dev/stderr
    help_short
    exit 1
}

# Loop for command line arguments, see:
#   http://stackoverflow.com/a/14203146/2666289
while [ ! -z "$1" ]
do
    key="$1"

    case $key in
        --no-shapefile)
            shapefile=false
            ;;
        -h|--help)
            help_long
            exit 0
            ;;
        *)
            input_file="$key"
            ;;
    esac
    shift # past argument or value
done

function download_shapefile() {

    if [ -f "inputs/land-polygons-split-4326/land_polygons.shp" ] && [ $(find "inputs/land-polygons-split-4326/inputs.shp" -mtime -30) ]; then
        echo "Land polygons exist and are newer than 30 days."
    else
        echo "Downloading land polygons..."
        rm -rf "inputs/land-polygons-split-4326"
        rm -f "inputs/land-polygons-split-4326.zip"
        wget -v -N -P "inputs" http://data.openstreetmapdata.com/land-polygons-split-4326.zip || exit 1
        unzip -o "inputs/land-polygons-split-4326.zip" -d "inputs"
        rm -f "inputs/land-polygons-split-4326.zip"
    fi

}

# Init OSM2Graph

if [ ! -e plugins/OSM2Graph ]; then
    error "OSM2Graph submodule does not exist, did you forget the --recursive option on clone?"
fi

if [ -e plugins/osm2graph.jar ]; then
    rm -f plugins/osm2graph.jar
fi

ln -s $(pwd)/plugins/OSM2Graph/osm2graph.jar $(pwd)/plugins/osm2graph.jar

# Download and extract shapefile
$shapefile || echo "Skipping shapefile download... "
$shapefile && download_shapefile
