#!zsh
# converts an aab to apk for easy testing
set -e

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

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

bundle=${1:-$(command ls -t *aab | head -n1)}
output=${bundle/.aab/.apks}
credentials=${2:-credentials.json}
test -f $bundle && echo "building apk for $bundle" || die "missing bundle"
test -f $credentials || die "missing credentials $credentials"

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

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\n" >&2
echo "  bundletool install-apks --apks ${output}" >&2
