#!/bin/sh -eu

# Update VMAP using FIG or MP from DIR_IN.
# Arguments: names with or without paths.
# No arguments: process all fig and mp files
#
# Version for mapsoft2, 2022-11-24

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

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

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

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

files=${@:-$IN_DIR/*.fig $IN_DIR/*.mp}

for i in $files; do
  [ -f "$i" ] || continue

  # name without directory and extension:
  name=${i%.*}
  name=${name##*/}
  ext=${i##*.}

  vmap=$VMAP_DIR/$name.$VMAP_EXT

  if [ ! -f "$vmap" ]; then
    echo " . skipping unknown file: $i"
    continue;
  fi

  if [ ! "$i" -nt "$vmap" ]; then
    echo " . skipping old file: $i"
    continue;
  fi

  echo " * updating from: $i"

  # save .bak file
  cp -f "$i" "$i.bak"

  args=""
  # mp has no labels
  if [ "$ext" = "mp" ]; then
    args="$args --keep_labels 1"
  fi

  if [ "$ext" = "fig" ]; then
    args="$args --fig_enc UTF-8"
  fi

  if [ "$CROP_NOM" = "1" ]; then
    args="$args --crop_nom $name"
  fi

  # update vmap from the input file
  $MS2VMAP "$i" --out "$vmap"\
    --types "$TYPEINFO" --define "$(vmap_defs "$name")"\
    --skip_unknown 1 --quite 0 \
    --update_labels 1 --fix_rounding 1 $args

  # save fig template
  if [ "$ext" = "fig" ]; then
    mkdir -p "$FIG_DIR"
    fig_tmpl="$FIG_DIR/$name.fig"
    cp -f -- "$i" "$fig_tmpl"
    $MS2VMAP --out "$fig_tmpl"\
      --types "$TYPEINFO" --define "$(vmap_defs "$name")"

    # update fig, restore old timestamp
    ot="$(stat "$i" -c %y)"
    vmaps_get_fig "$i"
    touch -d "$ot" "$i"
  fi

done
