#!/bin/sh -eu

# Make tiles
#
# 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 [ "$TILE_DIR" = "" ]; then
  echo "vmaps_tiles: TILE_DIR 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_tiles)}

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

##################################################
mkdir -p "$TILE_DIR"
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 tiles: $name"
  vmap_render_tiles "$name" "$brd"
  touch "$TILE_DIR/$name.tstamp"
  rm -f "$brd"
done

