<project name="build-android">
	<import file="build-set-globals.xml" as="globals" />
	<import file="build-settings.xml" as="settings" />
    <import file="${oepe.user.config.override.profile.dir.build.android.override}" optional="true" as="globals"/>

	<target name="init" depends="globals.init, maybeCreateKeyStore" />

    <target name="validateSign">
        <fail unless="key.store" message="PACKAGING: Missing requirement -- the key.store property must be set and point to your signing keystore." />
        <fail unless="key.store.password" message="PACKAGING: Missing requirement -- the key.store.password property must be set to the keystore password for key.store." />
        <fail unless="key.alias" message="PACKAGING: Missing requirement -- the key.store.alias property must be set to key alias to be used." />
        <fail unless="key.alias.password" message="PACKAGING: Missing requirement -- the key.store.alias.password property must be set to the keystore aliase password for key.store.alias." />
    </target>

	<target name="clean" depends="globals.init, cleanCustomImages">
		<delete dir="${adf.build.root.dir}/${out.dir}" failonerror="false"/>
	</target>

    <target name="cleanCustomImages">
         <delete failonerror="false">
            <fileset refid="adf.staging.res.customImages.fileset"/>
         </delete>
    </target>

    <target name="build" depends="init, build-if-debug-mode, build-if-release-mode"/>

    <target name="build-if-release-mode" if="oepe.adfmf.build.mode.is.release">
        <antcall target="build-release" inheritall="true" inheritrefs="true"/>
    </target>

    <target name="setup-build-release" depends="-set-release-mode, -release-obfuscation-check" />

    <target name="build-release" depends="updateWhitelist, updateDeviceAccess, updateAndroidConfig, processCordovaPlugins, setup-build-release, -dex, processCustomImages, copyProperties, settings.generateSettings, -package-resources, zipAssets" unless="oepe.build.mode.set">
        <property name="oepe.build.mode.set" value="true"/>
    </target>

    <target name="build-if-debug-mode" if="oepe.adfmf.build.mode.is.debug">
        <antcall target="build-debug" inheritall="true" inheritrefs="true" />
    </target>

    <target name="setup-build-debug" depends="-set-debug-files, -set-debug-mode, -debug-obfuscation-check">
        <echo message="Signing using key.store ${key.store} with alias ${key.alias}" />
    </target>

    <target name="build-debug" depends="updateWhitelist, updateDeviceAccess, updateAndroidConfig, processCordovaPlugins, setup-build-debug, -dex, processCustomImages, copyProperties, settings.generateSettings, -package-resources, zipAssets" unless="oepe.build.mode.set">
         <property name="oepe.build.mode.set" value="true"/>
    </target>

    <target name="processCustomImages" depends="copyCustomImages, maybeDecorateCustomImages" />

    <target name="copyProperties">
        <!-- possible that these don't exists, so failonerror=false -->
        <copy todir="${adf.build.root.dir}/lib" overwrite="true" failonerror="false">
            <fileset dir="${oepe.src.root.dir}/META-INF">
                <include name="*.properties" />
            </fileset>
        </copy>
        <!-- BUG 18692647 copy the app controller folder name to application.controller property in cvm.properties
             in staging -->
        <propertyfile
            file="${adf.staging.jvm.lib}/cvm.properties"
            comment="cvm properties">
            <entry key="application.controller" value="${oepe.adfmf.assembly.appControllerFolder}"/>
        </propertyfile>
    </target>

    <target name="copyCustomImages">
        <!-- if not already calculated, set the assembly project -->
        <property name="oepe.adfmf.assembly.project" location=".." />
        <property file="${oepe.adfmf.assembly.project}/res/android/android-resources.properties" />
        
        <!-- copy icons -->
         <copy todir="${adf.build.root.dir}"  failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.ldpi.icon}"></fileset>
            <mapper type="glob" from="*" to="res/drawable-ldpi/adfmf_icon.png"></mapper>
         </copy>
         <copy todir="${adf.build.root.dir}" failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.mdpi.icon}"></fileset>
            <mapper type="glob" from="*" to="res/drawable-mdpi/adfmf_icon.png"></mapper>
         </copy>
         <copy todir="${adf.build.root.dir}" failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.hdpi.icon}"></fileset>
            <mapper type="glob" from="*"  to="res/drawable-hdpi/adfmf_icon.png"></mapper>
         </copy>
         <copy todir="${adf.build.root.dir}" failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.xhdpi.icon}"></fileset>
            <mapper type="glob" from="*"  to="res/drawable-xhdpi/adfmf_icon.png"></mapper>
         </copy>

        <!-- copy splash screens -->
         <copy todir="${adf.build.root.dir}" failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.ldpi.portrait.splash}"></fileset>
            <mapper type="glob" from="*" to="res/drawable-port-ldpi/adfmf_loading.png"></mapper>
         </copy>

         <copy todir="${adf.build.root.dir}" failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.mdpi.portrait.splash}"></fileset>
            <mapper type="glob" from="*" to="res/drawable-port-mdpi/adfmf_loading.png"></mapper>
         </copy>

         <copy todir="${adf.build.root.dir}" failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.hdpi.portrait.splash}"></fileset>
            <mapper type="glob" from="*" to="res/drawable-port-hdpi/adfmf_loading.png"></mapper>
         </copy>

         <copy todir="${adf.build.root.dir}" failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.xhdpi.portrait.splash}"></fileset>
            <mapper type="glob" from="*" to="res/drawable-port-xhdpi/adfmf_loading.png"></mapper>
         </copy>

         <copy todir="${adf.build.root.dir}" failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.ldpi.landscape.splash}"></fileset>
            <mapper type="glob" from="*"  to="res/drawable-land-ldpi/adfmf_loading.png"></mapper>
         </copy>

         <copy todir="${adf.build.root.dir}" failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.mdpi.landscape.splash}"></fileset>
            <mapper type="glob" from="*"  to="res/drawable-land-mdpi/adfmf_loading.png"></mapper>
         </copy>

         <copy todir="${adf.build.root.dir}" failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.hdpi.landscape.splash}"></fileset>
            <mapper type="glob" from="*"  to="res/drawable-land-hdpi/adfmf_loading.png"></mapper>
         </copy>

         <copy todir="${adf.build.root.dir}" failonerror="false">
            <fileset file="${oepe.adfmf.assembly.project}/res/android/${oepe.adfmf.res.source.android.xhdpi.landscape.splash}"></fileset>
            <mapper type="glob" from="*"  to="res/drawable-land-xhdpi/adfmf_loading.png"></mapper>
         </copy>
    </target>

    <target name="maybeDecorateCustomImages" if="${oepe.userdebug.decorateCustomImages}">
        <script language="javascript" src="${oepe.bin.js.dir}/images-android.js"></script>
    </target>

    <target name="processCordovaPlugins" unless="oepe.build.ctrl.disable.processCordovaPlugins">
        <property name="adf.build.cordova.plugins.dir" location="${adf.build.base.dir}/../plugins"/>
    	<delete dir="${adf.build.cordova.plugins.dir}" includeemptydirs="true"/>
    	<path id="plugins_classpath">
    		<pathelement location="libs/deploy-utils.jar"/>
    	</path>
        <script language="javascript" manager="javax" src="${oepe.bin.js.dir}/cordova-plugins-android.js" classpathref="plugins_classpath"></script>
        <fail if="processCordovaPlugins.fail.message" message="${processCordovaPlugins.fail.message}" />
    </target>

    <target name="updateDeviceAccess" unless="oepe.build.ctrl.disable.updateDeviceAccess">
        <property file="${adf.build.root.dir}/device-access.properties" />
        <property file="${adf.staging.jvm.lib}/cvm.properties"/>
        <propertyset id="oepe.maf.device.access.propertyset">
          <propertyref prefix="oepe.maf.device.access"/>
        </propertyset>
        <script language="javascript" src="${oepe.bin.js.dir}/device-access-android.js"></script>
    </target>
    <target name="updateWhitelist" depends="globals.maybeInitWhitelistProperty, updateConfigXml" />

    <target name="updateConfigXml">
        <script language="javascript"  src="${oepe.bin.js.dir}/whitelist-android.js"  />
    </target>

    <target name="updateAndroidConfig" unless="oepe.build.ctrl.disable.updateAndroidConfig">
        <script language="javascript" src="${oepe.bin.js.dir}/android-config-update.js" />
    </target>

    <target name="zipAssets">
        <delete file="${adf.build.root.dir}/assets.zip" failonerror="false" />
        <zip update="true" destfile="${adf.build.root.dir}/assets.zip" basedir="${adf.build.root.dir}" includes="Configuration/**,.adf/**"/>
        <zip update="true" destfile="${adf.build.root.dir}/assets.zip" basedir="${adf.build.root.dir}/assets" includes="**" />
    </target>

    <target name="package" depends="package-if-release-mode, package-if-debug-mode" />

    <target name="package-if-release-mode" if="oepe.adfmf.build.mode.is.release">
        <antcall target="package-release" inheritall="true" inheritrefs="true" />
    </target>

    <target name="package-release" depends="init, setup-build-release, -build-setup">
        <!-- only package apk if *not* a library project -->
        <do-only-if-not-library elseText="Library project: do not package apk..." >
            <if condition="${build.is.instrumented}">
                <then>
                    <package-helper>
                        <extra-jars>
                            <!-- Injected from external file -->
                            <jarfile path="${emma.dir}/emma_device.jar" />
                        </extra-jars>
                    </package-helper>
                </then>
                <else>
                    <package-helper />
                </else>
            </if>
        </do-only-if-not-library>
        <zip update="true" destfile="${out.packaged.file}" basedir="${adf.build.root.dir}" includes="Configuration/**,.adf/**,lib/**,jvmlibs.zip,assets.zip,handlers.json" keepcompression="true"/>
        <antcall target="globals.-oepe-post-android-package" inheritall="true"  inheritrefs="true" />
    </target>

    <target name="package-if-debug-mode" if="oepe.adfmf.build.mode.is.debug">
        <antcall target="package-debug" inheritall="true" inheritrefs="true" />
    </target>

    <target name="package-debug" depends="init, setup-build-debug, -build-setup">
        <!-- only package apk if *not* a library project -->
        <do-only-if-not-library elseText="Library project: do not package apk..." >
            <if condition="${build.is.instrumented}">
                <then>
                    <package-helper>
                        <extra-jars>
                            <!-- Injected from external file -->
                            <jarfile path="${emma.dir}/emma_device.jar" />
                        </extra-jars>
                    </package-helper>
                </then>
                <else>
                    <package-helper />
                </else>
            </if>
        </do-only-if-not-library>
        <zip update="true" destfile="${out.packaged.file}" basedir="${adf.build.root.dir}" includes="Configuration/**,.adf/**,lib/**,jvmlibs.zip,assets.zip,handlers.json" keepcompression="true"/>
        <antcall target="globals.-oepe-post-android-package" inheritall="true"  inheritrefs="true" />
    </target>

    <target name="sign" depends="sign-if-release-mode, sign-if-debug-mode, sign-trace"/>

    <target name="sign-if-release-mode" if="oepe.adfmf.build.mode.is.release">
        <antcall target="sign-release" inheritall="true" inheritrefs="true" />
    </target>

    <target name="sign-release" depends="init, setup-build-release, -release-prompt-for-password, -release-sign, globals.-oepe-post-android-sign"/>

    <target name="sign-if-debug-mode" if="oepe.adfmf.build.mode.is.debug">
        <echo message="Signing debug apk using keystore ${key.store} with key alias ${key.store.alias}" />
        <antcall target="sign-debug" inheritall="true" inheritrefs="true" />
    </target>

    <target name="sign-debug" depends="init, setup-build-debug, -release-sign, globals.-oepe-post-android-sign" />

    <target name="sign-trace" if="oepe.build.info.trace.enabled">
        <jarsigner-verify file="${out.absolute.dir}/oepe-android-build-${oepe.adfmf.build.mode}.apk" />
    </target>
	<target name="check-device" description="Check whether device is running">
		<echo message="Checking whether android device is running"/>
		<exec executable="${adb}">
			<arg line="devices" />
		</exec>
		<exec executable="${adb}" failonerror="true" outputproperty="device.running.output">
			<arg line="${adb.device.arg}" />
			<arg value="get-state"/>
		</exec>
		<echo message="adb device status ${device.running.output}"/>
		<fail message="Cannot connect to the android device ${maf.deploy.device.id}">
		    <condition>
		    	<not>
		    	<equals arg1="${device.running.output}" arg2="device"/>
		    	</not>
		   </condition>
		</fail>
	</target>
    <target name="install" depends="check-device, uninstall, install-if-release-mode, install-if-debug-mode"/>
    
    <target name="install-if-release-mode" if="oepe.adfmf.build.mode.is.release">
        <echo message="install release mode to ${maf.deploy.device.id}" />
        <antcall target="installr" inheritall="true" inheritrefs="true" />
    </target>

    <target name="install-if-debug-mode" if="oepe.adfmf.build.mode.is.debug">
    	<execute-port-forwarding/>
        <echo message="install debug mode to ${maf.deploy.device.id}" />
        <antcall target="installd" inheritall="true" inheritrefs="true" />
    </target>

   <target name="maybeCreateKeyStore" if="oepe.adfmf.build.debug.autogen.android.keystore" depends="-ensureKeystoreProperties">
        <fail if="oepe.adfmf.build.mode.is.release" message="Can only auto-gen key store in debug mode"/>
        <fail unless="key.store" message="key.store already set, cannot auto-generate it" />
        <!-- the security info for the debug keystore are published by Google and well-known, so there
             is no issue putting them here in clear text -->
        <oepe_genkey keystorepath="${key.store}" alias="${key.alias}" storepass="${key.store.password}" keypass="${key.alias.password}" dname="CN=Android Debug,O=Android,C=US"/>
    </target>
    
    <target name="-ensureKeystoreProperties">
        <!-- called from maybeCreateKeyStore to ensure that the keystore properties are set
             even if the auto-gen debug.keystore file already exists -->
        <property name="key.store" location="${oepe.build.info.auto.keystore}" />
        <property name="key.store.password" value="android" />
        <property name="key.alias" value="androiddebugkey" />
        <property name="key.alias.password" value="android"/>
    </target>
    
	<target name="install-avd" depends="init">
		<android>
			<args>
				<arg value="create"/>
				<arg value="avd" />
				<arg value="-n" />
				<arg value="AdfMobileAvd" />
				<arg value="-t" />
				<arg value="android-17" />
				<arg value="--filter"/>
				<arg value="${target}" />
			</args>
		</android>
	</target>
	<target name="install-sdk" depends="init">
		<android>
			<args>
				<arg value="update"/>
				<arg value="sdk" />
				<arg value="-u" />
				<arg value="-a" />
				<arg value="--filter"/>
				<arg value="${target}" />
			</args>
		</android>
	</target>
	<target name="install-platform" depends="install-sdk">
		
	</target>
	
	<macrodef name="android">
		<element name="args"/>
		<sequential>
			<exec  executable="${android.tools.dir}/android${exe}">
				<args />
			</exec>
		</sequential>
	</macrodef>
	
    <macrodef name="oepe_genkey">
        <attribute name="keystorePath"/>
        <attribute name="alias"/>
        <attribute name="storepass"/>
        <attribute name="keypass" />
        <attribute name="dname" />
        <sequential>
            <exec executable="keytool">
                <arg value="-genkey" />
                <arg value="-v" />
                <arg value="-keystore" />
                <arg value="@{keystorepath}" />
                <arg value="-alias" />
                <arg value="@{alias}" />
                <arg value="-storepass" />
                <arg value="@{storepass}"/>
                <arg value="-keypass"/>
                <arg value="@{keypass}" />
                <arg value="-keyalg" />
                <arg value="RSA" />
                <arg value="-validity" />
                <arg value="14000" />
                <arg value="-dname" />
                <arg value="@{dname}" />
            </exec>
        </sequential>
    </macrodef>

    <macrodef name="jarsigner-verify">
        <attribute name="file" />
        <sequential>
            <exec executable="jarsigner">
                <arg value="-verify" />
                <arg value="-verbose" />
                <arg value="-certs" />
                <arg value="@{file}" />
            </exec>
        </sequential>
    </macrodef>
    
	<macrodef name="execute-port-forwarding">
		<sequential>
			<property file="${adf.staging.jvm.lib}/cvm.properties"/>
			<if>
				<condition>
					<and>
						<istrue value="${java.debug.enabled}" />
						<isset property="java.debug.port"/>
					</and>
				</condition>
				<then>
					<echo level="info">Running ADB port forwarding to ${java.debug.port} ...</echo>
					<exec executable="${adb}" failonerror="true">
						<arg line="${adb.device.arg}" />
						<arg value="forward" />
						<arg value="tcp:${java.debug.port}" />
						<arg value="tcp:${java.debug.port}" />
					</exec>
				</then>
			</if>
		</sequential>
	</macrodef>
</project>
