#!/usr/bin/env bash
# Usage: ./publish-minimum-versions.sh build test
#
# Parses minimum-versions.inc.sh to update template file /docs/minimum-versions.md.in.
# If /docs/minimum-versions.md is changed, commit and push changes
#

## START STANDARD BUILD SCRIPT INCLUDE
# adjust relative paths as necessary
THIS_SCRIPT="$(readlink -f "${BASH_SOURCE[0]}")"
. "${THIS_SCRIPT%/*}/builder.inc.sh"
## END STANDARD BUILD SCRIPT INCLUDE

. "${KEYMAN_ROOT}/resources/build/minimum-versions.inc.sh"

builder_describe "Build and test minimum-versions" \
  clean build test

builder_parse "$@"

generate_table() {
  echo ""
  echo "## minimum-versions.inc.sh Variables"
  echo ""
  echo "|          KEYMAN Variable          |     Value    |"
  echo "|-----------------------------------|--------------|"

  # Get all the shell variables named KEYMAN*VERSION
  strarr=( $(compgen -v KEYMAN | grep VERSION) )
  # echo "${strarr[@]}"

  for n in ${!strarr[@]}; do
    echo "| ${strarr[n]} | ${!strarr[n]} |"
  done

  echo ""
  echo "> ### This file is auto-generated by publish-minimum-versions.sh. Do not modify"
}

do_build() {
  cp "$KEYMAN_ROOT/docs/minimum-versions.md.in" "$KEYMAN_ROOT/docs/minimum-versions.md"
  generate_table >> "$KEYMAN_ROOT/docs/minimum-versions.md"
}

do_test() {
  # Verify that minimum-versions.md matches the generated data

  local new_table="$(mktemp)"
  cp "$KEYMAN_ROOT/docs/minimum-versions.md.in" "$new_table"
  generate_table >> "$new_table"
  diff --suppress-common-lines -yw "$KEYMAN_ROOT/docs/minimum-versions.md" "$new_table" || ( \
    rm "$new_table"
    builder_die "minimum-versions.md is not up to date. Please run 'publish-minimum-versions.sh build'"
  )

  rm  "$new_table"

  # TODO: this should have a test for each of the known machine-extractable versions.

  # language-subtag-registry

  local NEW_KEYMAN_VERSION_LANGUAGE_SUBTAG_REGISTRY="$(head ../standards-data/language-subtag-registry/language-subtag-registry -n 1 | cut -d" " -f 2 -)"
  if [[ "$NEW_KEYMAN_VERSION_LANGUAGE_SUBTAG_REGISTRY" != "$KEYMAN_VERSION_LANGUAGE_SUBTAG_REGISTRY" ]]; then
    builder_die "language-subtag-registry is version '$NEW_KEYMAN_VERSION_LANGUAGE_SUBTAG_REGISTRY' but minimum-version.inc.sh has version '$KEYMAN_VERSION_LANGUAGE_SUBTAG_REGISTRY'"
  fi
}

builder_run_action clean rm -f "$KEYMAN_ROOT/docs/minimum-versions.md"
builder_run_action build do_build
builder_run_action test do_test