#!/bin/bash

DEFAULT_OUTPUT_FOLDER=outputs

bounding_box=
debug=false

input_file=
output_name=

# FUNCTION help_short()
#
# Print short usage information.
function help_short() {
    echo "Usage: $0 [-h|--help] [-d|--debug] [-b|--bounding-box] [-o|--output OUTPUT_NAME] INPUT_FILE"
}

# FUNCTION help_long()
#
# Print detailed usage information.
function help_long() {
    help_short
    printf "\t-d,--debug\tEnable debug mode.\n"
    printf "\t-b,--bounding-box \tSpecify a bounding-box, either via a string or a file.\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
}

# FUNCTION warning(...)
#
# Print warning / information composed of arguments.
function warning() {
    echo "$0: $*" >> /dev/stderr
}

# FUNCTION run(...)
#
# Execute given command if debug mode is disabled, otherwize
# print it to stderr.
function run() {
    $debug && warning $*
    $debug || $*
}

# FUNCTION check_input_file()
#
# Check if input file exists and has read access.
function() check_input_file() {

    if [ -z "${input_file}" ]; then
        error_and_usage "Missing input file."
    fi

    if [ ! -e "${input_file}" ]; then
        error "${input_file} does not exist."
    fi

    if [ ! -e "${input_file}" ]; then
        error "${input_file} does not exist."
    fi

    if [ ! -r "${input_file}" ]; then
        error "${input_file} is not readable."
    fi

}

# FUNCTION check_output_file()
#
# Check output file.
function() check_input_file() {

    if [ -z "${output_file}" ]; then
        output_file=${DEFAULT_OUTPUT_FOLDER}/$(basename -s .pbf ${input_file})
        warning "No output file specific, switching to ${output_file}."
    fi

}

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

    case $key in
        -b|--bounding-box)
            bounding_box="$2"
            shift
            ;;
        -d|--debug)
            debug=true
            ;;
        -o|--output)
            output_name="$2"
            shift
            ;;
        -h|--help)
            help_long
            exit 0
            ;;
        *)
            input_file="$key"
            ;;
    esac
    shift # past argument or value
done

check_input_file
check_output_file
