/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2014-2015 Oracle and/or its affiliates. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License.  You can
 * obtain a copy of the License at
 * http://glassfish.java.net/public/CDDL+GPL_1_1.html
 * or packager/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at packager/legal/LICENSE.txt.
 *
 * GPL Classpath Exception:
 * Oracle designates this particular file as subject to the "Classpath"
 * exception as provided by Oracle in the GPL Version 2 section of the License
 * file that accompanied this code.
 *
 * Modifications:
 * If applicable, add the following below the License Header, with the fields
 * enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyright [year] [name of copyright owner]"
 *
 * Contributor(s):
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

/**
 * This task deletes all (unpacked) repackaged classes from target/classes directory.
 * Needed to be able to run `mvn install` repeatedly without cleaning the module.
 */
task deleteClasses(type: Delete) << {
    def dir = file ("" + buildDir
            + "/classes/"
            + shadedPackage.replaceAll('\\.', '/'))

    if (dir.isDirectory()) {
        dir.deleteDir()
    }
}

task generateProGuardConfig << {
    // import regexp pattern (strip method name from static imports) (shadedPackage is script parameter)
    def pattern = ~/.*(${shadedPackage}(\.[a-z0-9]+)*\.[A-Z][A-Za-z0-9]*)(\.[A-Za-z0-9]+)*.*/
    def classes = [] as Set

    // create module list from core ...
    def modules = []

    ['/core-common', '/core-client', '/core-server'].each {
        modules << absolutePath + it
    }

    // ... and all projects in connectors, containers, ext and media
    ['/connectors', '/containers', '/ext', '/media'].each {
        new File(absolutePath + it).listFiles().each {
            if (it.isDirectory()) {
                modules << it.absolutePath
            }
        }
    }

    // for each module ...
    modules.each {
        // ... get files in the (sub-)tree ... (absolutePath is script parameter)
        fileTree(it + '/src/main/java')
                // ... that includes only *.java files ...
                .include('**/*.java')
                .each { File file ->

                    // ... store class from import that match pattern into a set ...
                    file.eachLine {
                        def matcher = pattern.matcher(it)

                        if(matcher.matches()) {
                            classes << matcher.group(1)
                        }
                    }
        }
    }

    // ... and create ProGuard configuration file ... (confFile is script parameter)
    def conf = new File(confFile)
    conf.delete()
    conf.createNewFile()

    def ln = System.getProperty('line.separator')

    classes.each {
        conf << ("-keep public class ${it}${ln}")
        conf << ("-keepclassmembers public class ${it} { *; }${ln}")
    }
}

task copyShadedJar(type: Copy) {
    def version = project.hasProperty('jerseyVersion') ? jerseyVersion : ''
    from ('target') {
        include 'jersey-guava-' + version + '-shaded-sources.jar'
    }
    into 'target'

    rename {
        String fileName -> fileName.replace('shaded-sources', 'sources')
    }
}

task deleteShadedJar(type: Delete) {
    def version = project.hasProperty('jerseyVersion') ? jerseyVersion : ''
    delete ('target/jersey-guava-' + version + '-shaded-sources.jar')
}

task renameShadedJar(dependsOn: ['copyShadedJar', 'deleteShadedJar'])
deleteShadedJar.mustRunAfter copyShadedJar

copyShadedJar.onlyIf {project.hasProperty('jerseyVersion')}
deleteShadedJar.onlyIf {project.hasProperty('jerseyVersion')}
renameShadedJar.onlyIf {project.hasProperty('jerseyVersion')}
generateProGuardConfig.onlyIf {!project.hasProperty('jerseyVersion')}

