#!/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-full.inc.sh"
## END STANDARD BUILD SCRIPT INCLUDE

. "${KEYMAN_ROOT}/resources/build/minimum-versions.inc.sh"
. "${KEYMAN_ROOT}/resources/build/minimum-versions.tests.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
    case "${strarr[n]}" in
    KEYMAN_VERSION | KEYMAN_VERSION_MAJOR | KEYMAN_VERSION_MINOR | \
    KEYMAN_VERSION_PATCH | KEYMAN_VERSION_RELEASE | KEYMAN_VERSION_WIN | \
    KEYMAN_VERSION_TAG | KEYMAN_VERSION_WITH_TAG | \
    KEYMAN_VERSION_ENVIRONMENT | KEYMAN_VERSION_GIT_TAG | KEYMAN_VERSION_FOR_FILENAME)
      # ignore the variables that contain the Keyman version
      ;;
    *)
      echo "| ${strarr[n]} | ${!strarr[n]} |"
      ;;
    esac
  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"

  # From minimum-versions.tests.inc.sh
  minver_test_all
}

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