#!/bin/bash

# Mapsforge map creation (with coastlines) - Modified by Mikael

# Osmosis folder
OSMOSIS=$(pwd)/../bin/osmosis

# Input folder
INPUTS=$(pwd)

# Input PBF
inpbf=$1

if [ -z "${inpbf}" ]; then
    echo "Usage: $0: PBF_FILE"
    exit 1
fi

region_dir=$(dirname $(realpath ${inpbf}))
region_name=$(basename ${inpbf} .pbf)
region_name=$(basename ${region_name} .osm)
poly_file=${region_dir}/${region_name}.poly
bbox_file=${region_dir}/${region_name}.bbox

if [ ! -e "${inpbf}" ]; then
    echo "${inpbf} does not exist, you may want to download it from https://download.geofabrik.de/index.html."
    exit 1
fi

if [ ! -e "${poly_file}" ]; then
    poly_file=${INPUTS}/bbox/${region_name}.poly
fi

if [ ! -e "${poly_file}" ]; then
    echo "Unable to find polygon file, you may want to download it from https://download.geofabrik.de/index.html."
    exit 1
fi

if [ ! -e "$INPUTS/land-polygons-split-4326/land_polygons.shp" ]; then
    echo "Land polygons shapefile does not exist, did you forget to run init.sh?"
    exit 1
fi

# Bounds

olddir=$(pwd)
cd ${INPUTS}/mapsforge-creator

BBOX=$(perl poly2bb.pl "${poly_file}")
echo "$BBOX" > ${bbox_file}

BBOX=(${BBOX//,/ })
BOTTOM=${BBOX[0]}
LEFT=${BBOX[1]}
TOP=${BBOX[2]}
RIGHT=${BBOX[3]}


# Start position

CENTER=$(perl poly2center.pl "${poly_file}")
CENTER=(${CENTER//,/ })
LAT=${CENTER[0]}
LON=${CENTER[1]}

# Land

ogr2ogr -overwrite -progress -skipfailures -clipsrc $LEFT $BOTTOM $RIGHT $TOP "${region_dir}/${region_name}_land.shp" "$INPUTS/land-polygons-split-4326/land_polygons.shp"
if [ $? -ne 0 ]; then
    exit $?
fi


python shape2osm.py -l "${region_dir}/${region_name}_land" "${region_dir}/${region_name}_land.shp"

# Sea

sea_file="${region_dir}/${region_name}_sea.osm"
cp sea.osm "${sea_file}"
sed -i "s/\$BOTTOM/$BOTTOM/g" "${sea_file}"
sed -i "s/\$LEFT/$LEFT/g" "${sea_file}"
sed -i "s/\$TOP/$TOP/g" "${sea_file}"
sed -i "s/\$RIGHT/$RIGHT/g" "${sea_file}"

cd ${olddir}

CMD="$OSMOSIS --rb file=${inpbf} \
              --rx file=${sea_file} --s --m"
for f in ${region_dir}/${region_name}_land*.osm; do
  CMD="$CMD --rx file=$f --s --m"
done
CMD="$CMD --wb file=${region_dir}/${region_name}_merge.pbf omitmetadata=true"
echo $CMD
$CMD
