/**
 * Script for publishing
 * Source: https://getstream.io/blog/publishing-libraries-to-mavencentral-2021
 *
 *
 * If executed locally, create a local.properties files in the root directory
 * containing the required information below.
 * The secretKeyRingFile should be in binary format, e.g. gpg --export-secret-keys ID > ID.gpg
 * The PGP public key should be published, e.g. to https://keys.openpgp.org/
 */

// Create variables with empty default values
ext["signing.keyId"] = ''
ext["signing.password"] = ''
ext["signing.secretKeyRingFile"] = ''
ext["ossrhUsername"] = ''
ext["ossrhPassword"] = ''

File secretPropsFile = project.rootProject.file('local.properties')
if (secretPropsFile.exists()) {
    // Read local.properties file first if it exists
    Properties p = new Properties()
    new FileInputStream(secretPropsFile).withCloseable { is -> p.load(is) }
    p.each { name, value -> ext[name] = value }
} else {
    // Use system environment variables (e.g. for CI)
    ext["ossrhUsername"] = System.getenv('OSSRH_USERNAME')
    ext["ossrhPassword"] = System.getenv('OSSRH_PASSWORD')
    ext["signing.keyId"] = System.getenv('SIGNING_KEY_ID')
    ext["signing.password"] = System.getenv('SIGNING_PASSWORD')
    ext["signing.secretKeyRingFile"] = System.getenv('SIGNING_SECRET_KEY_RING_FILE')
}

// Set up Sonatype repository
nexusPublishing {
    repositories {
        sonatype {
            username = ossrhUsername
            password = ossrhPassword
            // new sonatype infrastructure as of 2025, see https://github.com/gradle-nexus/publish-plugin
            nexusUrl.set(uri("https://ossrh-staging-api.central.sonatype.com/service/local/"))
            snapshotRepositoryUrl.set(uri("https://central.sonatype.com/repository/maven-snapshots/"))
        }
    }
}

task updateVersionInReadme {
    doLast {
        ant.replaceregexp(match: '(eltos:simpledialogfragments:v?)\\d*(\\.\\d*)*', replace: '\\1'+VERSION, flags: 'g', byline: true) {
            fileset(dir: '.', includes: 'README.md')
        }
    }
}

task gitCommitAndTagVersion {
    doFirst {
        grgit.add(patterns: ['docs/javadoc', 'README.md', 'build.gradle'])
        grgit.commit(message: 'Release v'+VERSION, sign: false)
        grgit.tag.add(name:'v'+VERSION)
    }
}

task checkVersionAlreadyExists {
    doFirst {
        assert !grgit.tag.list().name.contains('v'+VERSION),
                "Version ${VERSION} defined in build.gradle already exists!"
    }
}

// Release pipeline
task postRelease {
    dependsOn gitCommitAndTagVersion
}
task doRelease {
    dependsOn 'simpledialogfragments:javadoc'
    dependsOn 'simpledialogfragments:publishToSonatype'
    dependsOn 'closeSonatypeStagingRepository'
    dependsOn updateVersionInReadme
    finalizedBy postRelease
}
task preRelease {
    dependsOn checkVersionAlreadyExists
    finalizedBy doRelease
}

task release {
    dependsOn preRelease
}
