import org.ysb33r.gradle.ivypot.OfflineRepositorySync

apply plugin: 'base'
apply plugin: 'fi.linuxbox.download.worker'
apply plugin: 'org.ysb33r.os'
apply plugin: 'org.ysb33r.ivypot'

repositories {
    mavenCentral()
}

tasks.named('syncRemoteRepositories', OfflineRepositorySync) {

    group 'Off-line repository'
    description 'Build Ivy repository from configurations'

    repoDetails { root = project.ext.offlineRepoRoot }

    inputs.file file("${rootProject.projectDir}/module-versions.properties")
    outputs.files project.ext.offlineRepoDescriptionFile
    outputs.files file("${project.ext.offlineRepoDescriptionFile}.kts")

    repositories {
        mavenCentral()
        maven { url 'https://plugins.gradle.org/m2/' }

        if (project.version.toString().endsWith('-SNAPSHOT')) {
            mavenLocal()
        }
    }

    binaryRepositories {
        nodejs {
            rootUri = 'https://nodejs.org/dist/'
            artifactPattern = 'v[revision]/[module]-v[revision]-[classifier].[ext]'
        }
    }

    addAllProjects()

    doLast {
        project.ext.offlineRepoDescriptionFile.withWriter { w ->
            w.println 'repositories {'
            w.print ' ' * 4
            w.println 'ivy {'
            w.print ' ' * 8
            w.println "name 'OfflineRepo'"
            w.print ' ' * 8
            w.println "layout 'gradle'"
            w.print ' ' * 8
            w.println "url '${file(repoRoot).absoluteFile.toURI()}'"
            w.print ' ' * 4
            w.println '}'
            w.println '}'
        }

        file("${project.ext.offlineRepoDescriptionFile}.kts").withWriter { w ->
            w.println 'repositories {'
            w.print ' ' * 4
            w.println 'ivy {'
            w.print ' ' * 8
            w.println 'name = "OfflineRepo"'
            w.print ' ' * 8
            w.println 'layout("gradle")'
            w.print ' ' * 8
            w.println "url = uri(\"${file(repoRoot).absoluteFile.toURI()}\")"
            w.print ' ' * 4
            w.println '}'
            w.println '}'
        }
    }

    onlyIf { !gradle.startParameter.offline }
}


task buildOfflineRepositories {
    group 'Off-line repository'
    description 'Cache dependencies off-line for testing'

    dependsOn syncRemoteRepositories
}

task cleanRepo(type: Delete) {
    delete project.ext.offlineRepoRoot
}

clean.delete = []
build.dependsOn buildOfflineRepositories
