/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * User Manual available at https://docs.gradle.org/5.6.3/userguide/tutorial_java_projects.html
 */

plugins {
    // Apply the application plugin to add support for building a CLI application
    id 'application'

    // Apply the java plugin to add support for Java
    id 'java'

    // Protoc plugin
    id 'com.google.protobuf' version '0.8.19'

    id 'eclipse'
    id 'idea'
}

compileJava.options.encoding = "UTF-8"
compileTestJava.options.encoding = "UTF-8"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}

version = '1.1.1'

var shouldGenerateProto = System.getenv("GENERATE_PROTO") == "true"
System.out.println(shouldGenerateProto ? "Generating proto files" : "Skipping proto generation")

repositories {
    mavenCentral()
    jcenter()
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.25.8'
    }

    plugins {
        quickbuf {
            artifact = 'us.hebi.quickbuf:protoc-gen-quickbuf:1.4'
        }
    }

    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.plugins {
                quickbuf {
                    //option 'store_unknown_fields=true'
                    outputSubDir = ''
                }
            }
        }
    }

    generatedFilesBaseDir = "$projectDir/src/generated/"
}

dependencies {
    implementation fileTree(dir: 'lib', include: ['*.jar'])

    implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.17'
    implementation group: 'ch.qos.logback', name: 'logback-core', version: '1.5.19'
    implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.5.19'

    implementation group: 'it.unimi.dsi', name: 'fastutil-core', version: '8.5.18'
    implementation group: 'org.reflections', name: 'reflections', version: '0.10.2'
    implementation group: 'com.esotericsoftware', name: 'reflectasm', version: '1.11.9'

    implementation group: 'com.google.code.gson', name: 'gson', version: '2.10.1'
    implementation group: 'us.hebi.quickbuf', name: 'quickbuf-runtime', version: '1.4'

    implementation group: 'io.javalin', name: 'javalin', version: '5.6.3'

    implementation group: 'dev.morphia.morphia', name: 'morphia-core', version: '2.3.9'
    implementation group: 'de.bwaldvogel', name: 'mongo-java-server', version: '1.47.0'
    implementation group: 'de.bwaldvogel', name: 'mongo-java-server-h2-backend', version: '1.47.0'
    
    implementation group: 'org.bouncycastle', name: 'bcprov-jdk18on', version: '1.82'

    protobuf files('proto/')

    compileOnly 'org.projectlombok:lombok:1.18.42'
    annotationProcessor 'org.projectlombok:lombok:1.18.42'
}

configurations.all {
    exclude group: 'org.slf4j', module: 'slf4j'
}

clean {
    if (shouldGenerateProto) {
        delete protobuf.generatedFilesBaseDir
    }
}

application {
    // Define the main class for the application
    mainClass.set('emu.nebula.Nebula')
}

run {
    // Set the standard input to wait for user input
    standardInput = System.in
}

jar {
    dependsOn 'injectGitHash'

    exclude '*.proto'
	
    exclude 'META-INF/*.SF'
    exclude 'META-INF/*.DSA'
    exclude 'META-INF/*.RSA'

    manifest {
        attributes 'Main-Class': 'emu.nebula.Nebula'
    }

    jar {
        archiveBaseName = 'Nebula'
        archiveVersion = ''
    }

    from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }

    duplicatesStrategy = DuplicatesStrategy.EXCLUDE

    from('src/main/java') {
        include '*.xml'
    }

    getDestinationDirectory().set(file("."))
}

sourceSets {
    main {
        proto {
            srcDir 'src/generated'
        }
        java {
            srcDir 'src/main/java'
        }
    }
}

idea {
    module {
        // proto files and generated Java files are automatically added as
        // source dirs.
        // If you have additional sources, add them here:
        sourceDirs += file('/proto/')
    }
}

eclipse {
    classpath {
        file.whenMerged { cp ->
            cp.entries.add( new org.gradle.plugins.ide.eclipse.model.SourceFolder('src/generated/main/', null) )
        }
    }
}

tasks.register('injectGitHash') {
    def gitCommitHash = {
        try {
            return 'git rev-parse --verify --short HEAD'.execute().text.trim()
        } catch (ignored) {
            return ''
        }
    }
    
    def gitCommitTime = {
        try {
            return 'git log -1 --format=%at --date=raw'.execute().text.trim()
        } catch (ignored) {
            return '0'
        }
    }

    new File(project.projectDir.getAbsolutePath() + '/src/main/java/emu/nebula/BuildConfig.java').text = """
package emu.nebula;

public final class BuildConfig {
	public static final String VERSION = \"${version}\";
    public static final String GIT_HASH = \"${gitCommitHash()}\";
    public static final String GIT_TIMESTAMP = \"${gitCommitTime()}\";
}
"""
}

task updateProto {
    group 'Build'
    description 'Cleans generated proto folder and regenerates protos'

    if (shouldGenerateProto) {
        dependsOn 'clean'
    }

    dependsOn 'generateProto'
}

processResources {
    dependsOn 'generateProto'
}
