#!/usr/bin/env bash
# converts an aab to apk for easy testing
set -euo pipefail

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

command -v jq 2>/dev/null >&2 || err "missing jq"
command -v bundletool 2>/dev/null >&2 || err "missing bundletool"

bundle=${1:-$(command ls -t ./*aab | head -n1)}
output=${bundle/.aab/.apks}
credentials=${2:-credentials.json}

test -f "$bundle" || err "missing bundle"
test -f "$credentials" || err "missing $credentials"

credential() {
  jq --raw-output --exit-status .android.keystore."$1" "$credentials" || err "missing $1 from $credentials"
}

bundletool build-apks \
  --bundle "$bundle" \
  --output "$output" \
  --ks "$(credential keystorePath)" \
  --ks-key-alias "$(credential keyAlias)" \
  --ks-pass "pass:$(credential keystorePassword)" \
  --key-pass "pass:$(credential keyPassword)"

echo "$output"
echo "install with" >&2
echo "" >&2
echo "    bundletool install-apks --apks ${output}" >&2
