/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.apache.lucene.gradle.ProfileResults;

def recordings = files()

if (Boolean.parseBoolean(propertyOrDefault("tests.profile", "false"))) {
  allprojects {
    tasks.withType(Test) {
      jvmArgs("-XX:StartFlightRecording=dumponexit=true,maxsize=250M,settings=" + rootProject.file("gradle/testing/profiling.jfc"),
              "-XX:+UnlockDiagnosticVMOptions",
              "-XX:+DebugNonSafepoints")
      // delete any previous profile results
      doFirst {
        project.delete fileTree(dir: workingDir, include: '*.jfr')
      }
      doLast {
        recordings = recordings.plus fileTree(dir: workingDir, include: '*.jfr')
      }
    }
  }

  gradle.buildFinished {
    if (!recordings.isEmpty()) {
      ProfileResults.printReport(recordings.getFiles().collect { it.toString() },
                                 propertyOrDefault(ProfileResults.MODE_KEY, ProfileResults.MODE_DEFAULT) as String,
                                 Integer.parseInt(propertyOrDefault(ProfileResults.STACKSIZE_KEY, ProfileResults.STACKSIZE_DEFAULT)),
                                 Integer.parseInt(propertyOrDefault(ProfileResults.COUNT_KEY, ProfileResults.COUNT_DEFAULT)),
                                 Boolean.parseBoolean(propertyOrDefault(ProfileResults.LINENUMBERS_KEY, ProfileResults.LINENUMBERS_DEFAULT)))
    }
  }
}