/********************************************************************************
 * Copyright (c) 2022, 2023 Contributors to the Eclipse Foundation
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 ********************************************************************************/
plugins {
    id 'java-library'
}

apply from: "$rootDir/gradle/java.gradle"

dependencies {

    def prefix = "${mat_deps_dir_path}/"

    implementation fileTree(prefix) {
        include "org.eclipse.osgi*.jar"
        include "org.eclipse.core.runtime*.jar"
        include "org.eclipse.mat.hprof*.jar"
        include "org.eclipse.equinox.preferences*.jar"
    }
}

@SuppressWarnings('GrMethodMayBeStatic')
def findHprofJarName() {
    for (String name : file(mat_deps_dir_path).list()) {
        if (name.contains('hprof')) {
            return name;
        }
    }
    throw new IllegalStateException("Hprof jar not found");
}

tasks.register('hookPreferences', Zip) {
    dependsOn compileJava
    def hprof = findHprofJarName()
    def preferences = 'org/eclipse/mat/hprof/ui/HprofPreferences.class'
    def access = 'org/eclipse/mat/hprof/extension/HprofPreferencesAccess.class'

    from(zipTree("${mat_deps_dir_path}/${hprof}")) {
        exclude preferences
    }

    from(file("${buildDir}/classes/java/main")) {
        include preferences
        include access
    }

    archiveFileName = hprof

    outputs.upToDateWhen {
        false
    }

    doLast {
        delete(file(file("${mat_deps_dir_path}/${hprof}")))

        copy {
            from(file("${buildDir}/distributions/${hprof}"))
            into(file(mat_deps_dir_path))
            duplicatesStrategy = DuplicatesStrategy.INCLUDE
        }
    }
}

jar {
    archiveBaseName.set("heap-dump-analysis-hook")
}