#!/usr/bin/env bash

# fail on errors
set -e

# Colors and formatting
RED='\033[1;31m'
GREEN='\033[1;32m'
BLUE='\033[1;34m'
NC='\033[0m' # No Color

# Get git root
readonly GIT_ROOT="$(git rev-parse --show-toplevel)"
# require that fastlanew is invoked from the top level directory of the repository
if [ "$(pwd)" != "$GIT_ROOT" ]; then
  echo -e "${RED}fastlanew must be invoked from the top level directory of the repository.${NC}"
  exit 1
fi

# Get expected fastlane version from GEMFILE
# gem "fastlane", "~> 2.227.2"
readonly FASTLANE_VERSION=$(grep -o 'fastlane", "~> [0-9]\+\.[0-9]\+\.[0-9]\+' Gemfile | sed 's/fastlane", "~> //')
export FASTLANE_SKIP_UPDATE_CHECK=0

if [[ "$(bundle exec fastlane --version)" != *"fastlane $FASTLANE_VERSION" ]]; then
  echo -e "${RED}Fastlane is not installed or the version is incorrect (expected $FASTLANE_VERSION). Please run ./INSTALL.${NC}"
  exit 1
fi

if [[ -z "${CI:-}" ]]; then
  export PATH="$(brew --prefix rbenv)/bin:$PATH"
  eval "$(rbenv init -)"
else
  export FASTLANE_SKIP_UPDATE_CHECK=1
fi

bundle exec fastlane "$@"
