#!/bin/sh

ErrorCheck () {
	if [ "$1" = "0" ]; then
		exit 0
	else
		echo "ERROR: yarn/webpack build failure. Check build log at https://teamcity.internal.justin.tv" >&2
		echo "##teamcity[message text='yarn/webpack build failure. Check build log at https://teamcity.internal.justin.tv']"
		echo "##teamcity[buildStatus status='Failed' text='yarn/webpack build failure. Check build log at https://teamcity.internal.justin.tv']"
		exit $1
	fi
}

if [ ! -z "$DEPENDENCY_ONLY" ]; then
  echo "Skipping build, only dependencies requested"
  exit 0
fi

if [ ! -z "$INTERNALIZATION_UPDATE" ]; then
  echo "Getting Internationalization Files"
  yarn teamcity:intl:update || (sleep 15 && yarn teamcity:intl:update)
  exit $?
fi

if [ ! -z "$DEV_ONLY" ]; then
  echo "Building only dev distribution"
	if [ ! -z "$API_OVERRIDE" ]; then
		yarn build -- --env.publicPath=https://static.twitchcdn.tech/ --env.manifestURL=https://static.twitchcdn.tech/config/manifest.json?v=1 --env.buildDir=dev --env.buildID=$TWILIGHT_BUILD_ID --env.api=$API_BASE_URL --env.gql=$GQL_BASE_URL || ErrorCheck $?
	else
		yarn build -- --env.publicPath=https://static.twitchcdn.tech/ --env.manifestURL=https://static.twitchcdn.tech/config/manifest.json?v=1 --env.buildDir=dev --env.buildID=$TWILIGHT_BUILD_ID || ErrorCheck $?
	fi
else
  if [ ! -z "$SHADOW_BUILD" ]; then
    echo "Building shadow test distribution"
    yarn build:shadow -- --env.publicPath=https://static.twitchcdn.tech/ --env.manifestURL=https://static.twitchcdn-shadow.net/config/manifest.json?v=1 --env.shadowTest --env.buildDir=testshadow  --env.buildID=$TWILIGHT_BUILD_ID || ErrorCheck $?

    echo "Building shadow distribution"
    yarn build:shadow -- --env.publicPath=https://static.twitchcdn-shadow.net/ --env.manifestURL=https://static.twitchcdn-shadow.net/config/manifest.json?v=1 --env.buildDir=shadow  --env.buildID=$TWILIGHT_BUILD_ID || ErrorCheck $?
  else
		# No longer used once we split dev and prod builds for master and experiments
    # echo "Building dev distribution"
    # yarn build -- --env.publicPath=https://static.twitchcdn.tech/ --env.buildDir=dev --env.buildID=$TWILIGHT_BUILD_ID || ErrorCheck $?

    echo "Building production distribution"
    yarn build:production -- --env.publicPath=https://static.twitchcdn.net/ --env.manifestURL=https://static.twitchcdn.net/config/manifest.json?v=1 --env.buildDir=production  --env.buildID=$TWILIGHT_BUILD_ID || ErrorCheck $?
  fi
fi
