import java.util.regex.Matcher
import java.util.regex.Pattern

// --------------- Plugins ---------------

plugins {
	// https://plugins.gradle.org/plugin/org.dyvil.dyvil-gradle
	id 'org.dyvil.dyvil-gradle' version '0.6.0-alpha.2' apply false
	// https://plugins.gradle.org/plugin/io.github.gradle-nexus.publish-plugin
	id 'io.github.gradle-nexus.publish-plugin' version '1.3.0'
}

// *************** Shared Configuration ***************

wrapper.setDistributionType(Wrapper.DistributionType.ALL)

// --------------- Constants ---------------

ext {
	libraryDependency = 'org.dyvil:library:0.48.1'

	getTagVersion = this.&getTagVersion
}

private String getTagVersion(String module = '', boolean release = hasProperty("DYVIL_RELEASE")) {
	if (!module.isEmpty() && !module.endsWith("/")) {
		module += '/'
	}

	final String tagOutput = 'git tag --sort=-version:refname'.execute([], rootDir).text
	final Pattern pattern = Pattern.compile("^${ module }v(.*)\$", Pattern.MULTILINE)
	final Matcher matcher = pattern.matcher(tagOutput)
	if (!matcher.find()) {
		throw new IllegalStateException("failed to find /$pattern/ in output:\n$tagOutput")
	}

	final String newestTag = matcher.group(0)
	final String newestVersion = matcher.group(1)
	if (release) {
		return newestVersion
	}

	final String commitCount = "git rev-list $newestTag.. --count".execute().text.trim()
	if (commitCount == "0") {
		return newestVersion
	}
	final String commitID = 'git rev-parse --short HEAD'.execute().text.trim()
	return newestVersion + '-' + commitCount + '-' + commitID
}

allprojects {
	apply from: rootProject.file('shared.build.gradle')
}

// *************** Configuration for Root Project ***************

// --------------- Publishing ---------------

nexusPublishing {
	repositories {
		sonatype()
	}
}

// --------------- Info ---------------

version = getTagVersion()
description = 'The Dyvil programming language.'

// --------------- Publication ---------------

project(':repl').afterEvaluate {
	jar.manifest.attributes("Main-Class": project(':repl').mainClassName)
}

dependencies {
	implementation libraryDependency
	implementation project(':compiler')
	implementation project(':repl')
	implementation project(':gensrc')
}
