<?xml version="1.0" encoding="utf-8"?>
<!--
** Template for the build targets common to all plugins
** ====================================================
**
** To override a property, add it to the plugin build.xml _before_
** this template has been imported.
** To override a target, add it _after_ this template has been imported.
**
** Paths are relative to the build.xml that imports this template.
**
-->
<project name="plugin_common" basedir="." xmlns:jacoco="antlib:org.jacoco.ant">

    <property name="josm"                   location="../../core/dist/josm-custom.jar"/>
    <property name="groovy.jar"             location="../00_core_tools/groovy-all-2.3.4.jar"/>
    <property name="plugin.build.dir"       location="build"/>
    <property name="plugin.test.dir"        location="test"/>
    <property name="plugin.src.dir"         location="src"/>
    <property name="plugin.lib.dir"         location="lib"/>
    <!-- this is the directory where the plugin jar is copied to -->
    <property name="plugin.dist.dir"        location="../../dist"/>
    <property name="ant.build.javac.target" value="1.7"/>
    <property name="ant.build.javac.source" value="1.7"/>
    <property name="plugin.jar"             location="${plugin.dist.dir}/${ant.project.name}.jar"/>

    <!--
    **********************************************************
    ** init - initializes the build
    **********************************************************
    -->
    <target name="init">
        <mkdir dir="${plugin.build.dir}"/>
    </target>
    <!--
    **********************************************************
    ** compile - compiles the source tree
    **********************************************************
    -->
    <target name="compile" depends="init">
        <echo message="compiling sources for ${plugin.jar} ..."/>
        <javac srcdir="src" debug="true" destdir="${plugin.build.dir}" includeantruntime="false" encoding="UTF-8">
            <compilerarg value="-Xlint:deprecation"/>
            <compilerarg value="-Xlint:unchecked"/>
            <classpath>
                <pathelement location="${josm}"/>
                <fileset dir="${plugin.lib.dir}" erroronmissingdir="no">
                    <include name="**/*.jar"/>
                </fileset>
            </classpath>
        </javac>
    </target>
    <!--
    **********************************************************
    ** setup-dist - copies files for distribution
    **********************************************************
    -->
    <target name="setup-dist-default">
        <copy todir="${plugin.build.dir}/resources" failonerror="no" includeemptydirs="no">
            <fileset dir="resources"/>
        </copy>
        <copy todir="${plugin.build.dir}/images" failonerror="no" includeemptydirs="no">
            <fileset dir="images"/>
        </copy>
        <copy todir="${plugin.build.dir}/data" failonerror="no" includeemptydirs="no">
            <fileset dir="data"/>
        </copy>
        <copy todir="${plugin.build.dir}">
            <fileset dir=".">
                <include name="README"/>
                <include name="LICENSE*"/>
                <include name="*GPL*"/>
            </fileset>
        </copy>
    </target>
    <target name="setup-dist">
        <antcall target="setup-dist-default" />
    </target>
    <!--
    **********************************************************
    ** dist - creates the plugin jar
    **********************************************************
    -->
    <target name="dist" depends="compile,revision">
        <echo message="creating ${ant.project.name}.jar ... "/>
        <antcall target="setup-dist" />
        <delete file="MANIFEST" failonerror="no"/>
        <manifest file="MANIFEST" mode="update">
            <attribute name="Plugin-Mainversion" value="${plugin.main.version}"/>
            <attribute name="Plugin-Version" value="${version.entry.commit.revision}"/>
            <attribute name="Plugin-Class" value="${plugin.class}" />
            <attribute name="Plugin-Description" value="${plugin.description}" />
            <attribute name="Plugin-Date" value="${version.entry.commit.date}" />
            <attribute name="Author" value="${plugin.author}"/>
        </manifest>
        <antcall target="add-manifest-attribute">
            <param name="manifest.attribute" value="Plugin-Link"/>
            <param name="propery.name" value="plugin.link"/>
            <param name="propery.value" value="${plugin.link}"/>
        </antcall>
        <antcall target="add-manifest-attribute">
            <param name="manifest.attribute" value="Plugin-Icon"/>
            <param name="propery.name" value="plugin.icon"/>
            <param name="propery.value" value="${plugin.icon}"/>
        </antcall>
        <antcall target="add-manifest-attribute">
            <param name="manifest.attribute" value="Plugin-Early"/>
            <param name="propery.name" value="plugin.early"/>
            <param name="propery.value" value="${plugin.early}"/>
        </antcall>
        <antcall target="add-manifest-attribute">
            <param name="manifest.attribute" value="Plugin-Requires"/>
            <param name="propery.name" value="plugin.requires"/>
            <param name="propery.value" value="${plugin.requires}"/>
        </antcall>
        <antcall target="add-manifest-attribute">
            <param name="manifest.attribute" value="Plugin-Stage"/>
            <param name="propery.name" value="plugin.stage"/>
            <param name="propery.value" value="${plugin.stage}"/>
        </antcall>
        <antcall target="additional-manifest" />
        <jar destfile="${plugin.jar}" basedir="${plugin.build.dir}" manifest="MANIFEST">
            <zipgroupfileset dir="${plugin.lib.dir}" includes="*.jar" erroronmissingdir="no"/>
        </jar>
        <delete file="MANIFEST" failonerror="no"/>
        <antcall target="post-dist" />
    </target>
    <target name="post-dist">
    	<!-- to be overidden by plugins that need to perform additional tasks on resulting jar -->
    </target>
    <target name="add-manifest-attribute" depends="check-manifest-attribute" if="have-${propery.name}">
        <manifest file="MANIFEST" mode="update">
            <attribute name="${manifest.attribute}" value="${propery.value}" />
        </manifest>
    </target>
    <!-- target to add additional entries, empty in commons -->
    <target name="additional-manifest">
    </target>
    <target name="check-manifest-attribute">
        <condition property="have-${propery.name}">
            <and>
                <isset property="${propery.name}"/>
                <not>
                    <equals arg1="${propery.value}" arg2=""/>
                </not>
                <not>
                    <equals arg1="${propery.value}" arg2="..."/>
                </not>
            </and>
        </condition>
    </target>
    <!--
    **********************************************************
    ** revision - extracts the current revision number for the
    **    file build.number and stores it in the XML property
    **    version.*
    **********************************************************
    -->
    <!--
      ** Initializes the REVISION.XML file from SVN information
    -->
    <target name="init-svn-revision-xml">
        <exec append="false" output="REVISION.XML" executable="svn" failifexecutionfails="false" resultproperty="svn.info.result">
            <env key="LANG" value="C"/>
            <arg value="info"/>
            <arg value="--xml"/>
            <arg value="."/>
        </exec>
        <condition property="svn.info.success">
            <equals arg1="${svn.info.result}" arg2="0" />
        </condition>
    </target>
    <!--
      ** Initializes the REVISION.XML file from git-svn information.
         Obtains the revision from the git-svn-id field.
    -->
    <target name="init-git-svn-revision-xml" unless="svn.info.success">
        <exec append="false" output="REVISION.XML" executable="git" failifexecutionfails="false" resultproperty="git.svn.info.result">
            <arg value="log"/>
            <arg value="-1"/>
            <arg value="--grep=git-svn-id"/>
            <!--
            %B:  raw body (unwrapped subject and body)
            %n:  new line
            %ai: author date, ISO 8601 format
            -->
            <arg value="--pretty=format:%B%n%ai"/>
            <arg value="HEAD"/>
        </exec>
        <replaceregexp file="REVISION.XML" flags="s"
                       match=".*git-svn-id: [^@]*@([0-9]+).*(\d{4}-\d{2}-\d{2}.\d{2}\:\d{2}\:\d{2}\s*[+-]\d{2}:?\d{2})\s*$"
                       replace="&lt;info&gt;&lt;entry&gt;&lt;commit revision=&quot;\1&quot;&gt;&lt;date&gt;\2&lt;/date&gt;&lt;/commit&gt;&lt;/entry&gt;&lt;/info&gt;"/>
       <condition property="git.svn.fail">
           <not>
               <and>
                   <equals arg1="${git.svn.info.result}" arg2="0" />
                   <length file="REVISION.XML" when="greater" length="1" />
               </and>
           </not>
       </condition>
   </target>
    <!--
      ** Initializes the REVISION.XML file from git (w/o svn) information.
         Uses Unix date as revision number.
    -->
    <target name="init-git-revision-xml" if="git.svn.fail">
        <exec append="false" output="REVISION.XML" executable="git" failifexecutionfails="false" resultproperty="git.info.result">
            <arg value="log"/>
            <arg value="-1"/>
            <arg value="--pretty=format:%at%n%ai"/>
            <arg value="HEAD"/>
        </exec>
        <replaceregexp file="REVISION.XML" flags="s"
                       match="\s*(\d*)\s+(\d{4}-\d{2}-\d{2}.\d{2}\:\d{2}\:\d{2}\s*[+-]\d{2}:?\d{2})\s*$"
                       replace="&lt;info&gt;&lt;entry&gt;&lt;commit revision=&quot;\1&quot;&gt;&lt;date&gt;\2&lt;/date&gt;&lt;/commit&gt;&lt;/entry&gt;&lt;/info&gt;"/>
       <condition property="git.fail">
           <not>
               <and>
                   <equals arg1="${git.info.result}" arg2="0" />
                   <length file="REVISION.XML" when="greater" length="1" />
               </and>
           </not>
       </condition>
    </target>
    <target name="init-revision-fallback" if="git.fail">
        <tstamp>
            <format property="current.time" pattern="yyyy-MM-dd'T'HH:mm:ss.SSS" />
        </tstamp>
        <echo file="REVISION.XML"><![CDATA[<info><entry><commit revision="UNKNOWN"><date>${current.time}</date></commit></entry></info>]]></echo>
    </target>
    <target name="revision" depends="init-svn-revision-xml, init-git-svn-revision-xml, init-git-revision-xml, init-revision-fallback">
      <xmlproperty file="REVISION.XML" prefix="version" keepRoot="false" collapseAttributes="true"/>
      <delete file="REVISION.XML"/>
    </target>
    <!--
    **********************************************************
    ** clean - clean up the build environment
    **********************************************************
    -->
    <target name="clean">
        <delete dir="${plugin.build.dir}"/>
        <delete file="${plugin.jar}"/>
    </target>
    <!--
    **********************************************************
    ** install - install the plugin in your local JOSM installation
    **********************************************************
    -->
    <target name="install" depends="dist">
        <property environment="env"/>
        <condition property="josm.plugins.dir" value="${env.APPDATA}/JOSM/plugins" else="${user.home}/.josm/plugins">
            <and>
                <os family="windows"/>
            </and>
        </condition>
        <copy file="${plugin.jar}" todir="${josm.plugins.dir}"/>
    </target>
    <!--
    ************************** Publishing the plugin *********************************** 
    -->
    <!--
    ** extracts the JOSM release for the JOSM version in ../core and saves it in the 
    ** property ${coreversion.info.entry.revision}
    **
    -->
    <target name="core-info">
        <exec append="false" output="core.info.xml" executable="svn" failifexecutionfails="false">
            <env key="LANG" value="C"/>
            <arg value="info"/>
            <arg value="--xml"/>
            <arg value="../../core"/>
        </exec>
        <xmlproperty file="core.info.xml" prefix="coreversion" keepRoot="true" collapseAttributes="true"/>
        <echo>Building against core revision ${coreversion.info.entry.revision}.</echo>
        <echo>Plugin-Mainversion is set to ${plugin.main.version}.</echo>
        <delete file="core.info.xml"/>
    </target>
    <!--
    ** commits the source tree for this plugin
    -->
    <target name="commit-current">
        <echo>Commiting the plugin source with message '${commit.message}' ...</echo>
        <exec append="true" output="svn.log" executable="svn" failifexecutionfails="false">
            <env key="LANG" value="C"/>
            <arg value="commit"/>
            <arg value="-m"/>
            <arg value="${commit.message}"/>
            <arg value="."/>
        </exec>
    </target>
    <!--
    ** updates (svn up) the source tree for this plugin
    -->
    <target name="update-current">
        <echo>Updating plugin source ...</echo>
        <exec append="true" output="svn.log" executable="svn" failifexecutionfails="false">
            <env key="LANG" value="C"/>
            <arg value="up"/>
            <arg value="."/>
        </exec>
        <echo>Updating ${plugin.jar} ...</echo>
        <exec append="true" output="svn.log" executable="svn" failifexecutionfails="false">
            <env key="LANG" value="C"/>
            <arg value="up"/>
            <arg value="../dist/${plugin.jar}"/>
        </exec>
    </target>
    <!--
    ** commits the plugin.jar 
    -->
    <target name="commit-dist">
        <echo>
    ***** Properties of published ${plugin.jar} *****
    Commit message    : '${commit.message}'
    Plugin-Mainversion: ${plugin.main.version}
    JOSM build version: ${coreversion.info.entry.revision}
    Plugin-Version    : ${version.entry.commit.revision}
    ***** / Properties of published ${plugin.jar} *****

    Now commiting ${plugin.jar} ...
    </echo>
        <exec append="true" output="svn.log" executable="svn" failifexecutionfails="false">
            <env key="LANG" value="C"/>
            <arg value="-m"/>
            <arg value="${commit.message}"/>
            <arg value="commit"/>
            <arg value="${plugin.jar}"/>
        </exec>
    </target>
    <!-- ** make sure svn is present as a command line tool ** -->
    <target name="ensure-svn-present">
        <exec append="true" output="svn.log" executable="svn" failifexecutionfails="false" failonerror="false" resultproperty="svn.exit.code">
            <env key="LANG" value="C"/>
            <arg value="--version"/>
        </exec>
        <fail message="Fatal: command 'svn --version' failed. Please make sure svn is installed on your system.">
            <!-- return code not set at all? Most likely svn isn't installed -->
            <condition>
                <not>
                    <isset property="svn.exit.code"/>
                </not>
            </condition>
        </fail>
        <fail message="Fatal: command 'svn --version' failed. Please make sure a working copy of svn is installed on your system.">
            <!-- error code from SVN? Most likely svn is not what we are looking on this system -->
            <condition>
                <isfailure code="${svn.exit.code}"/>
            </condition>
        </fail>
    </target>

    <target name="publish" depends="ensure-svn-present,core-info,commit-current,update-current,clean,dist,commit-dist">
    </target>
	
    <path id="test.classpath">
        <fileset dir="../00_core_test_lib">
            <include name="**/*.jar"/>
        </fileset>
        <fileset dir="${plugin.test.dir}/lib" erroronmissingdir="no">
            <include name="**/*.jar"/>
        </fileset>
        <fileset dir="lib" erroronmissingdir="no">
            <include name="**/*.jar"/>
        </fileset>
        <pathelement path="../../core/test/build/unit"/>
        <pathelement path="${josm}"/>
        <pathelement path="${plugin.jar}"/>
        <pathelement path="${groovy.jar}"/>
    </path>
    <macrodef name="init-test-preferences">
        <attribute name="testfamily"/>
        <sequential>
            <copy file="${plugin.test.dir}/config/preferences.template.xml" tofile="${plugin.test.dir}/config/@{testfamily}-josm.home/preferences.xml"/>
            <replace file="${plugin.test.dir}/config/@{testfamily}-josm.home/preferences.xml" encoding="UTF-8" token="@OSM_USERNAME@" value="${osm.username}"/>
            <replace file="${plugin.test.dir}/config/@{testfamily}-josm.home/preferences.xml" encoding="UTF-8" token="@OSM_PASSWORD@" value="${osm.password}"/>
        </sequential>
    </macrodef>
    <target name="test-init">
        <mkdir dir="${plugin.test.dir}/build"/>
        <mkdir dir="${plugin.test.dir}/build/unit"/>
        <mkdir dir="${plugin.test.dir}/report"/>
        <init-test-preferences testfamily="unit"/>
    </target>
    <target name="test-clean">
        <delete dir="${plugin.test.dir}/build"/>
        <delete dir="${plugin.test.dir}/report"/>
        <delete file="${plugin.test.dir}/jacoco.exec" />
        <delete file="${plugin.test.dir}/config/unit-josm.home/preferences.xml" />
        <delete dir="${plugin.test.dir}/config/unit-josm.home/cache" failonerror="false"/>
    </target>
    <macrodef name="call-groovyc">
        <attribute name="testfamily"/>
        <element name="cp-elements"/>
        <sequential>
            <groovyc srcdir="${plugin.test.dir}/@{testfamily}" destdir="${plugin.test.dir}/build/@{testfamily}" encoding="UTF-8">
                <classpath>
                    <cp-elements/>
                </classpath>
                <javac target="1.7" source="1.7" debug="on">
                    <compilerarg value="-Xlint:all"/>
                    <compilerarg value="-Xlint:-serial"/>
                </javac>
            </groovyc>
        </sequential>
    </macrodef>
    <target name="test-compile" depends="test-init,dist">
        <taskdef name="groovyc" classname="org.codehaus.groovy.ant.Groovyc" classpath="${groovy.jar}"/>
        <call-groovyc testfamily="unit">
            <cp-elements>
                <path refid="test.classpath"/>
            </cp-elements>
        </call-groovyc>
    </target>
    <macrodef name="call-junit">
        <attribute name="testfamily"/>
        <sequential>
            <echo message="Running @{testfamily} tests with JUnit"/>
            <jacoco:coverage destfile="${plugin.test.dir}/jacoco.exec">
                <junit printsummary="yes" fork="true" forkmode="once">
                    <sysproperty key="josm.home" value="${plugin.test.dir}/config/@{testfamily}-josm.home"/>
                    <sysproperty key="josm.test.data" value="${plugin.test.dir}/data"/>
                    <sysproperty key="java.awt.headless" value="true"/>
                    <sysproperty key="suppressPermanentFailure" value="${suppressPermanentFailure}"/>
                    <classpath>
                        <path refid="test.classpath"/>
                        <pathelement path="${plugin.test.dir}/build/unit"/>
                        <pathelement path="${plugin.test.dir}/build/@{testfamily}"/>
                        <pathelement path="${plugin.test.dir}/config"/>
                    </classpath>
                    <formatter type="plain"/>
                    <formatter type="xml"/>
                    <batchtest fork="yes" todir="${plugin.test.dir}/report">
                        <fileset dir="${plugin.test.dir}/build/@{testfamily}" includes="**/*Test.class"/>
                    </batchtest>
                </junit>
            </jacoco:coverage>
        </sequential>
    </macrodef>
    <target name="test" depends="test-compile" 
        description="Run unit tests. OSM API (TEST) account shall be set with -Dosm.username and -Dosm.password">
        <taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml" classpath="../00_core_tools/jacocoant.jar" />
        <call-junit testfamily="unit"/>
    </target>
	
    <target name="runjosm" depends="install">
        <java jar="${josm}" fork="true">
        </java>
    </target>

    <target name="profilejosm" depends="install">
        <nbprofiledirect>
        </nbprofiledirect>
        <java jar="${josm}" fork="true">
            <jvmarg value="${profiler.info.jvmargs.agent}"/>
        </java>
    </target>
    <!--
    ** shows a help text 
    -->
    <target name="help">
        <echo>
    You can use following targets:
    * dist        This default target builds the plugin jar file
    * clean       Cleanup automatical created files
	* test        Run unit tests (if any)
    * publish     Checkin source code, build jar and checkin plugin jar
                  (requires proper entry for SVN commit message!)
    * install     Install the plugin in current system
    * runjosm     Install plugin and start josm
    * profilejosm Install plugin and start josm in profiling mode
    
    There are other targets, which usually should not be called manually.
        </echo>
    </target>
</project>

