#!/bin/bash -ex
#
# script/cibuild
# SwiftGit2
#
# Executes the build and runs tests for Mac and iOS. Designed to be invoked by
# Travis as a matrix build so that the two platform builds can run in parallel.
#
# Dependent tools & scripts:
# - script/bootstrap
# - script/update_libssl_ios
# - [xcodebuild](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/xcodebuild.1.html)
# - xcpretty (gem)
# - xcpretty-travis-formatter (gem)
#
# Environment Variables:
# - SCHEME: specifies which Xcode scheme to build. Set to one of the following:
#   - SwiftGit2-OSX
#   - SwiftGit2-iOS
# - TRAVIS: indicates when the build is being run by travis, used to invoke
#           the xcpretty-travis-formatter gem for output.

if [ -z "$SCHEME" ]; then
  echo "The SCHEME environment variable is empty. Please set this to one of:"
  echo "- SwiftGit2-OSX"
  echo "- SwiftGit2-iOS"
  exit 1
fi


##
## Configuration Variables
##

set -o pipefail
SCRIPT_DIR=$(dirname "$0")
XCWORKSPACE="SwiftGit2.xcworkspace"
XCODE_OPTIONS=$(RUN_CLANG_STATIC_ANALYZER=NO ONLY_ACTIVE_ARCH=NO CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO)

if [ -n "$TRAVIS" ]; then
    # Use a special formatter when running on TravisCI
    XCPRETTY_FORMAT_OPTIONS="-f `xcpretty-travis-formatter`"
else
    XCPRETTY_FORMAT_OPTIONS="--color"
fi

##
## Build Process
##

echo "*** Bootstrapping..."
"$SCRIPT_DIR/bootstrap"

if [ "$SCHEME" == "SwiftGit2-OSX" ]; then
  echo "*** Building and testing $SCHEME..."
  echo

  xcodebuild -workspace "$XCWORKSPACE" \
    -scheme "$SCHEME" \
    ${XCODE_OPTIONS[*]} \
    build test \
    2>&1 | xcpretty $XCPRETTY_FORMAT_OPTIONS
elif [ "$SCHEME" == "SwiftGit2-iOS" ]; then
  echo "*** Prebuilding OpenSSL"
  "$SCRIPT_DIR/update_libssl_ios"

  echo "*** Creating a simulator for testing..."
  # Create a new simulator device and reference it by id to avoid xcodebuild exit status 70 with the following errors: 
  #   "The requested device could not be found because no available devices matched the request."
  #   "The requested device could not be found because multiple devices matched the request."
  SIMULATOR_NAME="Custom Simulator"
  DEVICE_ID=com.apple.CoreSimulator.SimDeviceType.iPhone-X
  RUNTIME_ID=com.apple.CoreSimulator.SimRuntime.iOS-11-4
  DESTINATION_ID=$(xcrun simctl create "$SIMULATOR_NAME" $DEVICE_ID $RUNTIME_ID)

  echo "*** Building and testing $SCHEME..."
  echo

  xcodebuild -workspace "$XCWORKSPACE" \
    -scheme "$SCHEME" \
    -destination "id=$DESTINATION_ID" \
    -sdk iphonesimulator \
    ${XCODE_OPTIONS[*]} \
    build test \
    2>&1 | xcpretty $XCPRETTY_FORMAT_OPTIONS
fi
