#!/bin/bash -eu
#
# script/version
# mas
#
# Displays the current marketing version of mas.
#

mas_dir="$(readlink -fn "$(dirname "${BASH_SOURCE:-"${0}"}")/..")"

if ! cd -- "${mas_dir}"; then
  printf $'Error: Could not cd into mas directory: %s\n' "${mas_dir}" >&2
  exit 1
fi

if [[ -z "${MAS_VERSION:-}" ]] && git describe >/dev/null 2>&1; then
  # Use last tag if MAS_VERSION environment variable is unset or empty
  MAS_VERSION=$(git describe --abbrev=0 --tags 2>/dev/null || true)
fi
echo "${MAS_VERSION#v}"

if [[ "${#}" -ge 1 && "${1}" == '--write' ]]; then
  # Write new version into swift package
  cat <<EOF >Sources/mas/Package.swift
/// Generated by \`script/version\`.
enum Package {
    static let version = "${MAS_VERSION#v}"
}
EOF
fi
