#!/usr/bin/env zsh
set -e
setopt verbose

die() {
  echo "$@" >&2
  exit 1
}

android_home="${ANDROID_HOME:-$HOME/Library/Android/sdk}"
test -d "$android_home" || die 'Could not find ANDROID_HOME directory, please set in your path'
PATH=$android_home/emulator:$android_home/platform-tools:$PATH

command -v adb 2>/dev/null >&2 || due 'mising adb, needed to install apk. try adding $ANDROID_HOME/platform-tools to your path'
command -v aab2apks 2>/dev/null >&2 || die 'missing aab2apks, needed to convert the aab to an apks. try adding rti-scripts to your path'
command -v bundletool 2>/dev/null >&2 || die 'missing bundletool, needed to install the apks. try `brew install bundletool`'

date
test -n "$SKIP_EAS" || RELEASE_ENV=production npm run eas -- build --platform android --profile production --non-interactive --skip-project-configuration
appurl=$(RELEASE_ENV=production npm run eas -- build:list --platform android --limit 1 --status finished | rg Artifact | awk '{print $2}')
test -n "$appurl"
app=$(basename $appurl)
test -f "$app" || curl -OLs "$appurl"
test -f "$app"

if [[ "$app" =~ 'apk$' ]]; then
  adb install "$app"
else
  apks=${app/\.aab/\.apks}
  test -f "$apks" || ./aab2apks.zsh $app
  test -f "$apks"
  bundletool install-apks --apks "$apks"
fi

avd=$(emulator -list-avds | head -n1)
test -n "$avd"
emulator -avd $avd || true
adb shell monkey -p com.sonymusic.sma 1
adb logcat -s 'ReactNativeJS:*'
