#!/bin/bash -e
# start.sh
#
# Starts simulator/emulator

platform=''
brand=''
env=''
device=''
release=''

argumentsCount=$#
for(( argumentIndex=1; argumentIndex<=argumentsCount; argumentIndex+=2 )); do
  argumentKey=${!argumentIndex}
  argumentValueIndex=$((argumentIndex+1))
  argumentValue=${!argumentValueIndex}
  if [[ $argumentKey == "--platform" ]]; then
    platform=$argumentValue
  elif [[ $argumentKey == "--brand" ]]; then
    brand=$argumentValue
  elif [[ $argumentKey == "--env" ]]; then
    env=$argumentValue
  elif [[ $argumentKey == "--device" ]]; then
    device=$argumentValue
  elif [[ $argumentKey == "--release" ]]; then
    release=$argumentValue
  else
    echo "Unknown argument $argumentKey"
    exit 1
  fi
done

yarn create:autogenerated:env
yarn create:native:resources $brand $env $platform

if [[ $platform == "ios" ]]; then
  command="yarn react-native run-ios"
  if [[ $device != '' ]]; then
    command="$command --simulator \"$device\""
  fi
  if [[ $release == 'true' ]]; then
    command="$command --mode Release"
  fi
  eval $command
elif [[ $platform == "android" ]]; then
  applicationId=$(yarn --silent android:application:id $brand $env)
  if [[ $device == '' ]]; then
    yarn react-native run-android --appId $applicationId
  else
    yarn react-native run-android --appId $applicationId --deviceId "$device"
  fi
else
  echo "Can't run simulator/emulator for platform: $platform"
  exit 1
fi
