#!/bin/sh -eu

# Render individual maps into mbtiles
#
# Arguments: names with or without paths.
# No arguments: process all new vmap files
# Version for mapsoft2, 2025-01-03

##################################################

# read global configuration and functions
. vmaps.sh ||:

# read local configuration
. ./vmaps.conf ||:

if [ "$MBTILES" = "" ]; then
  echo "vmaps_rend_mbtiles: MBTILES is not set, exiting"
  exit
fi

##################################################

# Update colormap if needed
if [ ! -f "$CMAP" ]; then
  echo "Colormap is missing. Updating $CMAP"
  vmap_update_cmap $CMAP_SRC $CMAP
fi

##################################################
# If argument list is empty, find only old files
files=${@:-$(list_vmap_nt_mbtiles)}

# check that git is clean (print warnings, ignore result)
vmap_git_status_list $files ||:

##################################################
for i in $files; do
  name=${i%.*}
  name=${name##*/}
  vmap="$VMAP_DIR/$name.$VMAP_EXT"
  if [ ! -f "$vmap" ]; then
    echo "can't find file: $vmap"
    continue
  fi
  brd=$(mktemp vmaps_tiles_XXXX.gpx)
  ms2conv $BRD_DIR/*.gpx -o "$brd"

  # update tiles
  echo "Rendering into mbtiles: $name"
  vmap_render_mbtiles "$name" "$brd"
  touch -r "$vmap" "$MBTILES"
  rm -f "$brd"
done

