plugins {
    id 'base'
    alias(catalog.plugins.gradle.docker)
}

import com.bmuschko.gradle.docker.tasks.image.DockerBuildImage
import com.bmuschko.gradle.docker.tasks.image.DockerPushImage
import com.bmuschko.gradle.docker.tasks.image.DockerTagImage


configurations {
    docker {
        canBeResolved = true
        transitive = false
        visible = false
        canBeConsumed = false
    }
}

dependencies {
    docker project(path: ':rbcs-cli', configuration: 'release')
    docker project(path: ':rbcs-server-memcache', configuration: 'release')
    docker project(path: ':rbcs-server-redis', configuration: 'release')
    docker project(path: ':rbcs-server-otel', configuration: 'release')
}

Provider<Task> cleanTaskProvider = tasks.named(BasePlugin.CLEAN_TASK_NAME) {}

Provider<Copy> prepareDockerBuild = tasks.register('prepareDockerBuild', Copy) {
    dependsOn cleanTaskProvider
    group = 'docker'
    into project.layout.buildDirectory.file('docker')
    from(configurations.docker)
    from(files('Dockerfile', 'rbcs-cli.sh'))
    from(rootProject.file('conf')) {
        include 'logback.xml'
    }
}

Provider<DockerBuildImage> dockerBuild = tasks.register('dockerBuildImage', DockerBuildImage) {
    group = 'docker'
    dependsOn prepareDockerBuild
    images.add('gitea.woggioni.net/woggioni/rbcs:latest')
    images.add("gitea.woggioni.net/woggioni/rbcs:${version}")
}

Provider<DockerTagImage> dockerTag = tasks.register('dockerTagImage', DockerTagImage) {
    group = 'docker'
    repository = 'gitea.woggioni.net/woggioni/rbcs'
    imageId = 'gitea.woggioni.net/woggioni/rbcs:latest'
    tag = version
}

Provider<DockerTagImage> dockerTagMemcache = tasks.register('dockerTagMemcacheImage', DockerTagImage) {
    group = 'docker'
    repository = 'gitea.woggioni.net/woggioni/rbcs'
    imageId = 'gitea.woggioni.net/woggioni/rbcs:memcache'
    tag = "${version}-memcache"
}

Provider<DockerPushImage> dockerPush = tasks.register('dockerPushImage', DockerPushImage) {
    group = 'docker'
    dependsOn dockerTag, dockerTagMemcache
    registryCredentials {
        url = getProperty('docker.registry.url')
        username = 'woggioni'
        password = System.getenv().get("PUBLISHER_TOKEN")
    }
    images = [dockerTag.flatMap{ it.tag }, dockerTagMemcache.flatMap{ it.tag }]
}
