plugins {
  id("java")
  id("checkstyle")
  id("com.github.spotbugs").version("6.0.12")
  id("org.cadixdev.licenser").version("0.6.1")
  id("com.gradleup.shadow").version("8.3.6")
}

setGroup("net.elytrium")
setVersion("1.1.7")

compileJava {
  getOptions().setEncoding("UTF-8")
}

java {
  setSourceCompatibility(JavaVersion.VERSION_17)
  setTargetCompatibility(JavaVersion.VERSION_17)
}

repositories {
  mavenCentral()

  maven {
    setName("elytrium-repo")
    setUrl("https://maven.elytrium.net/repo/")
  }
  maven {
    setName("papermc-repo")
    setUrl("https://repo.papermc.io/repository/maven-public/")
  }
}

dependencies {
  compileOnly("net.elytrium.limboapi:api:$limboapiVersion")
  compileOnly("com.velocitypowered:velocity-api:$velocityVersion")
  annotationProcessor("com.velocitypowered:velocity-api:$velocityVersion")
  compileOnly("com.velocitypowered:velocity-proxy:$velocityVersion")
  compileOnly("io.netty:netty-handler:$nettyVersion")
  implementation("net.elytrium:serializer:$serializerVersion")
}

shadowJar {
  getArchiveClassifier().set("")

  relocate("net.elytrium.commons.velocity", "net.elytrium.limboapi.thirdparty.commons.velocity")
  relocate("net.elytrium.commons.kyori", "net.elytrium.limboapi.thirdparty.commons.kyori")
}

license {
  setHeader(file("HEADER.txt"))
}

checkstyle {
  setToolVersion("10.1")
  setConfigFile(file("${this.getRootDir()}/config/checkstyle/checkstyle.xml"))
  setConfigProperties("configDirectory": "${this.getRootDir()}/config/checkstyle")

  // The build should immediately fail if we have errors.
  setMaxErrors(0)
  setMaxWarnings(0)
}

spotbugsMain {
  setExcludeFilter(file("${this.getRootDir()}/config/spotbugs/suppressions.xml"))

  reports {
    html {
      getRequired().set(true)
      getOutputLocation().set(file("${this.getBuildDir()}/reports/spotbugs/main/spotbugs.html"))
      setStylesheet("fancy-hist.xsl")
    }
  }
}

sourceSets.main.getJava().srcDir(
    getTasks().register("generateTemplates", Copy) {
      task -> {
        String version = getVersion().contains("-") ? "${getVersion()} (git-${getCurrentShortRevision()})" : getVersion()
        task.getInputs().properties("version": version)
        task.from(file("src/main/templates")).into(getLayout().getBuildDirectory().dir("generated/sources/templates"))
        task.expand("version": version)
      }
    }.map {
      it.getOutputs()
    }
)

assemble.dependsOn(shadowJar)

String getCurrentShortRevision() {
  OutputStream outputStream = new ByteArrayOutputStream()
  exec {
    if (System.getProperty("os.name").toLowerCase().contains("win")) {
      commandLine("cmd", "/c", "git rev-parse --short HEAD")
    } else {
      commandLine("bash", "-c", "git rev-parse --short HEAD")
    }

    setStandardOutput(outputStream)
  }

  return outputStream.toString().trim()
}
