// If multiple valid ones, find the one which matches the most specifically.  I.e.,
  // XXXXXXXXXX.com.example.* will match over XXXXXXXXXX.* for com.example.TestApp
  // TODO(user): Account for differences between development and distribution certificates.
  @VisibleForTesting
  static Optional<ProvisioningProfileMetadata> getBestProvisioningProfile(
      ImmutableSet<ProvisioningProfileMetadata> profiles,
      String bundleID,
      Optional<String> provisioningProfileUUID,
      Optional<String> prefix) {
    int bestMatchLength = -1;
    Optional<ProvisioningProfileMetadata> bestMatch =
        Optional.<ProvisioningProfileMetadata>absent();

    for (ProvisioningProfileMetadata profile : profiles) {
      if (provisioningProfileUUID.isPresent()
          && profile.getUUID().equals(provisioningProfileUUID.get())) {
        return Optional.<ProvisioningProfileMetadata>of(profile);
      }

      if (profile.getExpirationDate().after(new Date())) {
        Pair<String, String> appID = profile.getAppID();

        LOG.debug("Looking at provisioning profile " + profile.getUUID() + "," + appID.toString());

        if (!prefix.isPresent() || prefix.get().equals(appID.getFirst())) {
          String profileBundleID = appID.getSecond();
          boolean match;
          if (profileBundleID.endsWith("*")) {
            // Chop the ending * if wildcard.
            profileBundleID = profileBundleID.substring(0, profileBundleID.length() - 1);
            match = bundleID.startsWith(profileBundleID);
          } else {
            match = (bundleID.equals(profileBundleID));
          }

          if (match && profileBundleID.length() > bestMatchLength) {
            bestMatchLength = profileBundleID.length();
            bestMatch = Optional.<ProvisioningProfileMetadata>of(profile);
          }
        }
      }
    }

    LOG.debug("Found provisioning profile " + bestMatch.toString());
    return bestMatch;
  }