import org.apache.tools.ant.taskdefs.condition.Os
import org.apache.tools.ant.filters.*

def appBundlerJar = 'freeplane_framework/mac-appbundler/appbundler-1.0.jar'
ant.taskdef(
    name: "appbundler",
    classname: 'com.oracle.appbundler.AppBundlerTask',
    classpath: appBundlerJar,
    onerror: "report"
)

def macAppPropertiesFile = file('macapp.properties')

Properties macAppProperties = new Properties()
if (macAppPropertiesFile.exists())
{
    macAppProperties.load(new FileInputStream(macAppPropertiesFile))
}

task macDist {}

def defineMacBuildTasks = {boolean includeJavaRuntime -> 
    def taskName = {base -> includeJavaRuntime ? base + '_jre' : base}
    def bin4mac = taskName(rootDir.path + '/BIN4mac')
    def macappfullpath = new File(bin4mac, 'Freeplane.app').absoluteFile
    
    def macosxapp = tasks.create (taskName('macosxapp')) {
		mustRunAfter binZip

		doFirst {
		
			if(! binZip.archivePath.exists())
				ant.fail("File ${binZip.archivePath.path} not found")
		
			delete bin4mac + '/Freeplane.app'
			mkdir bin4mac
			
			def zipExtracted = globalBin+'-extracted'
			delete zipExtracted
			mkdir zipExtracted
			
			copy {
				from(zipTree(binZip.archivePath))
				into(zipExtracted)
			}
			
			def globalBinExtracted = zipExtracted + '/' + file(zipExtracted).list()[0]

			ant.appbundler(
				outputdirectory: bin4mac,
				name: 'Freeplane',
				displayname: 'Freeplane',
				mainclassname: 'org.freeplane.launcher.Launcher',
				shortversion: distVersion,
				copyright: "Freeplane ${distVersion}",
				identifier: 'org.freeplane.core',
				icon: 'freeplane_framework/mac-appbundler/freeplane.icns',
				signature: '????'
			) {
				if (includeJavaRuntime) {
					if(macAppProperties['macapp.jdk.home'] != null) {
						runtime(dir: macAppProperties['macapp.jdk.home'])
					}
					else {
						def javaHomeJre = System.properties['java.home']
						def javaHome = javaHomeJre - ~/\/jre$/
						runtime(dir: javaHome)
					}
				}
				classpath(dir: globalBinExtracted, includes: '*.jar')
				option(value: "-Xmx512m")
				option(value: "-Dapple.laf.useScreenMenuBar=true")
				option(value: "-Xdock:name=Freeplane")
			}

			def dist_macos_info = macappfullpath.path + '/Contents/Info.plist'
			ant.xslt(in: new File(dist_macos_info),
				style: new File('freeplane_framework/mac-appbundler/mac_info_plist.xslt'),
				out: new File(dist_macos_info + '2')
			)
			java.nio.file.Files.move(java.nio.file.Paths.get(dist_macos_info + '2'),
									 java.nio.file.Paths.get(dist_macos_info),
					   java.nio.file.StandardCopyOption.REPLACE_EXISTING)

			def macjavafullpath = macappfullpath.path + '/Contents/Java'
			copy {
				from(globalBinExtracted) {
					 exclude('**/*.bat')
					 exclude('**/*.exe')
					 exclude('*.jar')
	 				exclude('license.txt')
				}
				into(macjavafullpath)
			}

			def macresourcesfullpath = macappfullpath.path + '/Contents/Resources'
			copy {
				 from('freeplane_framework/mac-appbundler') {
					 include('freeplanedoc.icns')
				 }
				 into(macresourcesfullpath)
			}
			delete zipExtracted
        }
    }

    def signMacApp= tasks.create (taskName('signMacApp'), Exec) {
        onlyIf { Os.isFamily(Os.FAMILY_MAC) && macAppProperties['macapp.codesign.identity'] != null}
 
        commandLine 'codesign', '--deep', '-s', macAppProperties['macapp.codesign.identity'], '-v', macappfullpath.path

        dependsOn macosxapp
    }

   def dmg4mac= tasks.create (taskName('dmg4mac'), Exec) {
        onlyIf { Os.isFamily(Os.FAMILY_MAC) }
        def dmgPath = globalDist + taskName('/freeplane_app') + '-' + distVersion + '.dmg';
        doFirst { 
            mkdir globalDist 
            file(dmgPath).delete()
        } 

        commandLine 'hdiutil', 'create', '-srcfolder', macappfullpath.path,
            dmgPath

        dependsOn macosxapp, signMacApp
    }

    def zip4mac = tasks.create (taskName('zip4mac'), Zip) {
        destinationDir = new File(globalDist)
        archiveName = taskName('freeplane_macos_bin') + '-' + distVersion + '.zip'

        from(bin4mac) {
            exclude('**/JavaAppLauncher')
        }
        from(bin4mac) {
            include('**/JavaAppLauncher')
            fileMode = 0775
        }

        into('freeplane-' + distVersion)
        dependsOn macosxapp
    }
    
    def cleanMac = tasks.create (taskName('cleanMac'), Delete) {
        delete bin4mac
    }

    if (Os.isFamily(Os.FAMILY_MAC)) {
        macDist.dependsOn dmg4mac
    }
    else {
        macDist.dependsOn zip4mac
    }
    
    clean.dependsOn cleanMac
}

if (Os.isFamily(Os.FAMILY_MAC)) {
    defineMacBuildTasks(true)
}
defineMacBuildTasks(false)
