import org.doomedsociety.gradlecpp.GradleCppUtils
import org.apache.commons.io.FilenameUtils

void _copyFileToDir(String from, String to) {
	if (!project.file(from).exists()) {
		println 'WARNING: Could not find: ' + from;
		return;
	}

	if (!project.file(to).exists()) {
		project.file(to).mkdirs();
	}

	def dst = new File(project.file(to), FilenameUtils.getName(from))
	GradleCppUtils.copyFile(project.file(from), dst, false)
}

void _copyFile(String from, String to) {
	if (!project.file(from).exists()) {
		println 'WARNING: Could not find: ' + from;
		return;
	}

	GradleCppUtils.copyFile(project.file(from), project.file(to), false)
}

task publishPrepareFiles << {
	def pubRootDir = project.file('publish/publishRoot')
	if (pubRootDir.exists()) {
		if (!pubRootDir.deleteDir()) {
			throw new RuntimeException("Failed to delete ${pubRootDir}")
		}
	}

	pubRootDir.mkdirs()
	project.file('publish/publishRoot/metamod/addons/metamod').mkdirs()

	_copyFileToDir('publish/metamod.dll', 'publish/publishRoot/metamod/addons/metamod/')
	//_copyFileToDir('publish/metamod.pdb', 'publish/publishRoot/metamod/addons/metamod/')
	_copyFile('publish/metamod_i386.so', 'publish/publishRoot/metamod/addons/metamod/metamod_i386.so')

	project.file('publish/publishRoot/metamod/sdk').mkdirs()
	copy {
		from 'metamod/src/dllapi.h'
		into 'publish/publishRoot/metamod/sdk'
	}
	copy {
		from 'metamod/src/engine_api.h'
		into 'publish/publishRoot/metamod/sdk'
	}
	copy {
		from 'metamod/src/enginecallbacks.h'
		into 'publish/publishRoot/metamod/sdk'
	}
	copy {
		from 'metamod/src/h_export.h'
		into 'publish/publishRoot/metamod/sdk'
	}
	copy {
		from 'metamod/src/meta_api.h'
		into 'publish/publishRoot/metamod/sdk'
	}
	copy {
		from 'metamod/src/mutil.h'
		into 'publish/publishRoot/metamod/sdk'
	}
	copy {
		from 'metamod/src/plinfo.h'
		into 'publish/publishRoot/metamod/sdk'
	}
	copy {
		from 'metamod/extra/config.ini'
		into 'publish/publishRoot/metamod/addons/metamod/'
	}
	copy {
		from 'metamod/extra/example'
		into 'publish/publishRoot/metamod/example_plugin'
	}
	copy {
		from 'publish/publishRoot/metamod/sdk'
		into 'publish/publishRoot/metamod/example_plugin/include/metamod'
	}
}

task publishPackage(type: Zip, dependsOn: 'publishPrepareFiles') {
	baseName = "metamod_${project.version}"
	destinationDir file('publish')
	from 'publish/publishRoot/metamod'
}

task doPackage {
	dependsOn 'publishPackage'
}