#!zsh
# converts an aab to apk for easy testing

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"

bundletool build-apks \
  --bundle $bundle \
  --output $output \
  --ks $(jq -r '.android.keystore.keystorePath' $credentials) \
  --ks-key-alias $(jq -r '.android.keystore.keyAlias' $credentials) \
  --ks-pass pass:$(jq -r '.android.keystore.keystorePassword' $credentials) \
  --key-pass pass:$(jq -r '.android.keystore.keyPassword' $credentials)

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