String kind
String releaseTitle
if (project.name == 'plugin-gradle') {
	kind = 'gradle'
	releaseTitle = 'Gradle Plugin'
} else if (project.name == 'plugin-maven') {
	kind = 'maven'
	releaseTitle = 'Maven Plugin'
} else {
	assert project == rootProject
	kind = 'lib'
	releaseTitle = 'Lib'
}

// the root project and plugins have their own changelogs
apply plugin: 'com.diffplug.spotless-changelog'
spotlessChangelog {
	changelogFile 'CHANGES.md'
	// need -Prelease=true in order to do a publish
	appendDashSnapshotUnless_dashPrelease=true

	branch        'release'
	tagPrefix     "${kind}/"
	commitMessage "Published ${kind}/{{version}}" // {{version}} will be replaced
	tagMessage "{{changes}}"
	runAfterPush "gh release create ${kind}/{{version}} --title '${releaseTitle} v{{version}}' --notes-from-tag"
}

if (project == rootProject) {
	gradle.taskGraph.whenReady { taskGraph ->
		def changelogPushTasks = taskGraph.allTasks.stream()
				.filter { t -> t.name == 'changelogPush' }
				.map { t -> t.path }
				.toList()
		if (changelogPushTasks.size() > 1) {
			// make sure only one changelog gets published per tag/commit
			throw new IllegalArgumentException("Run changelogPush one at a time:\n" + changelogPushTasks.join('\n'))
		} else if (changelogPushTasks.size() == 1) {
			boolean isPlugin = (changelogPushTasks[0] == ':plugin-gradle:changelogPush') || (changelogPushTasks[1] == ':plugin-maven:changelogPush')
			// if the one thing being published is a plugin
			if (isPlugin) {
				// make sure there aren't any unreleased changes in lib
				if (!rootProject.spotlessChangelog.parsedChangelog.noUnreleasedChanges()) {
					if (!("true".equals(rootProject.findProperty('ignoreUnreleasedLib')))) {
						throw new IllegalArgumentException(
						"You're going to publish ${changelogPushTasks[0]}, but there are unreleased features in lib!\n" +
						"You should run :changelogPush first!  Else you'll be missing out on:\n" +
						"${rootProject.spotlessChangelog.parsedChangelog.unreleasedChanges()}\n" +
						"If it's okay to miss those and link against the old ${rootProject.spotlessChangelog.versionLast} then " +
						"add -PignoreUnreleasedLib=true")
					}
				}
			}
		}
	}
}
