#!/bin/sh -eu

# Make img+mp files in IMG_DIR dir
#
# 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 [ "$IMG_DIR" = "" ]; then
  echo "vmaps_tiles: IMG_DIR is not set, exiting"
  exit
fi

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

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

##################################################
mkdir -p "$IMG_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

  mp="$IMG_DIR/$name.mp"
  mpz="$IMG_DIR/$name.mp.zip"
  img="$IMG_DIR/$name.img"

  echo "Making MP and IMG: $name"

  # generate MP
  mp_id=$(echo $name | md5sum | head -c6 | tr a-z A-Z)
  mp_id=$(echo -e "ibase=16\n$mp_id\n" | bc)
  vmap_render_mp "$name" "$mp" "$mp_id"

  # generate IMG
  $CGPSM "$mp" -o "$img"
  # generate mp.zip
  zip -j "$mpz" "$mp"
  rm -f "$mp"
done

