#!/usr/bin/env bash

# Unoffical Bash "strict mode"
# http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail
IFS=$'\t\n' # Stricter IFS settings

error_exit() {
  printf "%s\\n" "$1"
  exit "${2:-1}" # default exit status 1
}

profile_cmd() {
  local command
  local version
  local filename

  command=${1:-}
  version=${2:-}

  version_slug="$(echo "$version" | cut -f3 -d/)"
  command_slug="$(echo "$command" | tr ' ' '-')"
  filename="$command_slug-$version_slug.csv"

  hyperfine --export-csv "$filename" "$command"
}

project_dir=${1:-}
output_dir=${2:-}

# Verify project directory is provided
if [ -z "$project_dir" ]; then
    error_exit "Project directory must be specified"
fi

# Verify output directory is provided
if [ -z "$output_dir" ]; then
    error_exit "Output directory must be specified"
fi

# Change to project dir so we can use git
cd "$project_dir"

# Iterate over all tags
git for-each-ref --format="%(refname)" --sort=creatordate refs/tags | \
while read -r tag
do
  # Checkout tag
  git checkout "$tag"
  echo "==== Checked out $tag. Benchmarking commands..."

  # Profile commands for this version
  profile_cmd 'asdf current' "$tag" || true
  profile_cmd 'asdf which lua' "$tag" || true
  profile_cmd 'asdf where lua' "$tag" || true
  profile_cmd 'asdf exec lua -v' "$tag" || true
  profile_cmd 'asdf reshim' "$tag" || true
done
