plugins {
    id 'java-library'
    id 'base'
    id 'maven-publish'
}

group = 'com.frostwire'

base {
    archivesName = 'jlibtorrent'
}
// Just changing version here should be all that's necessary to bump the version on the library
// Dynamic from tag for Github workflow, fallback for local testing/building binaries
version = System.getenv('RELEASE_VERSION') ?: System.getenv('GITHUB_REF_NAME')?.replace('release/', '') ?: '2.0.12.7'

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
    sourceCompatibility = JavaVersion.VERSION_21
    targetCompatibility = JavaVersion.VERSION_21
    withSourcesJar()
    withJavadocJar()
    compileJava.options.encoding = "UTF-8"
    compileTestJava.options.encoding = "UTF-8"
}

// Ensure jar task depends on sourcesJar and javadocJar
tasks.named('jar') {
    dependsOn tasks.named('sourcesJar')
    dependsOn tasks.named('javadocJar')
}

// make build stop at the first error
tasks.withType(JavaCompile).configureEach {
    options.compilerArgs << "-Xmaxerrs" << "1"
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'junit:junit:4.13.2'

    def os = org.gradle.internal.os.OperatingSystem.current()
    def arch = System.getProperty('os.arch').toLowerCase()
    def is_arm64 = arch == "aarch64" || arch == "arm64"
    def is_x86_64 = arch == "amd64" || arch == "x86_64"

    def flavor = 'windows'

    if (os.isMacOsX()) {
        flavor = is_arm64 ? 'macosx-arm64' : 'macosx-x86_64'
    } else if (os.isLinux()) {
        if (is_arm64) {
            flavor = 'linux-arm64'
        } else if (is_x86_64) {
            flavor = 'linux-x86_64'
        } else {
            flavor = 'linux-x86_64'  // default fallback
        }
    }

    testImplementation files("build/libs/jlibtorrent-${flavor}-${version}.jar")
}

def hostNativeSourcesPresent = {
    def os = org.gradle.internal.os.OperatingSystem.current()
    def arch = System.getProperty('os.arch').toLowerCase()
    def isArm64 = arch == 'aarch64' || arch == 'arm64'
    def isX86_64 = arch == 'amd64' || arch == 'x86_64'

    if (os.isMacOsX()) {
        return !fileTree(dir: 'swig/bin/release/macosx',
                include: isArm64 ? 'arm64/*libjlibtorrent.arm64.dylib'
                        : 'x86_64/*libjlibtorrent.x86_64.dylib').isEmpty()
    }

    if (os.isLinux()) {
        return !fileTree(dir: 'swig/bin/release/linux',
                include: isArm64 ? 'arm64/*libjlibtorrent.so'
                        : (isX86_64 ? 'x86_64/*libjlibtorrent.so' : 'x86_64/*libjlibtorrent.so'))
                .isEmpty()
    }

    if (os.isWindows()) {
        return !fileTree(dir: 'swig/bin/release/windows', include: '**/*jlibtorrent.dll').isEmpty()
    }

    return false
}

tasks.withType(Test).configureEach {
    systemProperty "java.library.path", "."
}

tasks.test {
    outputs.upToDateWhen { false }
    testLogging {
        events "passed", "skipped", "failed", "standard_out"
    }
    onlyIf {
        hostNativeSourcesPresent()
    }
}

tasks.register('nativeMacOSArm64Jar', Zip) {
    destinationDirectory = layout.buildDirectory.dir("libs")
    archiveBaseName = 'jlibtorrent-macosx-arm64'
    archiveExtension = 'jar'
    from fileTree(dir: 'swig/bin/release/macosx', excludes: ['**/ed25519', '**/src'], include: 'arm64/*libjlibtorrent.arm64.dylib')
    into 'lib/'
    rename(".dylib", "-${version}.dylib")
}

tasks.register('nativeMacOSX86_64Jar', Zip) {
    destinationDirectory = layout.buildDirectory.dir("libs")
    archiveBaseName = 'jlibtorrent-macosx-x86_64'
    archiveExtension = 'jar'
    from fileTree(dir: 'swig/bin/release/macosx', excludes: ['**/ed25519', '**/src'], include: 'x86_64/*libjlibtorrent.x86_64.dylib')
    into 'lib/'
    rename(".dylib", "-${version}.dylib")
}

tasks.register('nativeWindowsX86_64Jar', Zip) {
    destinationDirectory = layout.buildDirectory.dir("libs")
    archiveBaseName = 'jlibtorrent-windows'
    archiveExtension = 'jar'
    from fileTree(dir: 'swig/bin/release/windows', excludes: ['**/ed25519', '**/src'], include: '**/*jlibtorrent.dll')
    into 'lib/'
    rename(".dll", "-${version}.dll")
}

tasks.register('nativeLinuxX86_64Jar', Zip) {
    destinationDirectory = layout.buildDirectory.dir("libs")
    archiveBaseName = 'jlibtorrent-linux-x86_64'
    archiveExtension = 'jar'
    from fileTree(dir: 'swig/bin/release/linux', excludes: ['**/ed25519', '**/src'], include: 'x86_64/*libjlibtorrent.so')
    into 'lib/x86_64/'
    rename(".so", "-${version}.so")
}

tasks.register('nativeLinuxArm64Jar', Zip) {
    destinationDirectory = layout.buildDirectory.dir("libs")
    archiveBaseName = 'jlibtorrent-linux-arm64'
    archiveExtension = 'jar'
    from fileTree(dir: 'swig/bin/release/linux', excludes: ['**/ed25519', '**/src'], include: 'arm64/*libjlibtorrent.so')
    into 'lib/arm64/'
    rename(".so", "-${version}.so")
}

tasks.register('nativeAndroidArmJar', Zip) {
    destinationDirectory = layout.buildDirectory.dir("libs")
    archiveBaseName = 'jlibtorrent-android-arm'
    archiveExtension = 'jar'
    from fileTree(dir: 'swig/bin/release/android', include: 'armeabi-v7a/libjlibtorrent.so')
    into 'lib/'
    rename(".so", "-${version}.so")
}

tasks.register('nativeAndroidX86Jar', Zip) {
    destinationDirectory = layout.buildDirectory.dir("libs")
    archiveBaseName = 'jlibtorrent-android-x86'
    archiveExtension = 'jar'
    from fileTree(dir: 'swig/bin/release/android', include: 'x86/libjlibtorrent.so')
    into 'lib/'
    rename(".so", "-${version}.so")
}

tasks.register('nativeAndroidArm64Jar', Zip) {
    destinationDirectory = layout.buildDirectory.dir("libs")
    archiveBaseName = 'jlibtorrent-android-arm64'
    archiveExtension = 'jar'
    from fileTree(dir: 'swig/bin/release/android', include: 'arm64-v8a/libjlibtorrent.so')
    into 'lib/'
    rename(".so", "-${version}.so")
}

tasks.register('nativeAndroidX64Jar', Zip) {
    destinationDirectory = layout.buildDirectory.dir("libs")
    archiveBaseName = 'jlibtorrent-android-x86_64'
    archiveExtension = 'jar'
    from fileTree(dir: 'swig/bin/release/android', include: 'x86_64/libjlibtorrent.so')
    into 'lib/'
    rename(".so", "-${version}.so")
}

// Declare explicit dependencies for compileTestJava on native jar tasks
// This must come AFTER all native jar tasks are registered
tasks.named('compileTestJava').configure {
    def os = org.gradle.internal.os.OperatingSystem.current()
    def arch = System.getProperty('os.arch').toLowerCase()
    def is_arm64 = arch == "aarch64" || arch == "arm64"
    def is_x86_64 = arch == "amd64" || arch == "x86_64"

    if (os.isMacOsX()) {
        if (is_arm64) {
            dependsOn 'nativeMacOSArm64Jar'
        } else {
            dependsOn 'nativeMacOSX86_64Jar'
        }
    } else if (os.isLinux()) {
        if (is_arm64) {
            dependsOn 'nativeLinuxArm64Jar'
        } else if (is_x86_64) {
            dependsOn 'nativeLinuxX86_64Jar'
        } else {
            dependsOn 'nativeLinuxX86_64Jar'  // default fallback
        }
    } else if (os.isWindows()) {
        dependsOn 'nativeWindowsX86_64Jar'
    }
}

// Clean task for nativeMacOSArm64Jar
tasks.register('cleanNativeMacOSArm64Jar', Delete) {
    delete layout.buildDirectory.file("libs/jlibtorrent-macosx-arm64-${version}.jar")
}

// Clean task for nativeMacOSX86_64Jar
tasks.register('cleanNativeMacOSX86_64Jar', Delete) {
    delete layout.buildDirectory.file("libs/jlibtorrent-macosx-x86_64-${version}.jar")
}

// Clean task for nativeWindowsX86_64Jar
tasks.register('cleanNativeWindowsX86_64Jar', Delete) {
    delete layout.buildDirectory.file("libs/jlibtorrent-windows-${version}.jar")
}

// Clean task for nativeLinuxX86_64Jar
tasks.register('cleanNativeLinuxX86_64Jar', Delete) {
    delete layout.buildDirectory.file("libs/jlibtorrent-linux-x86_64-${version}.jar")
}

// Clean task for nativeLinuxArm64Jar
tasks.register('cleanNativeLinuxArm64Jar', Delete) {
    delete layout.buildDirectory.file("libs/jlibtorrent-linux-arm64-${version}.jar")
}

// Clean task for nativeAndroidArmJar
tasks.register('cleanNativeAndroidArmJar', Delete) {
    delete layout.buildDirectory.file("libs/jlibtorrent-android-arm-${version}.jar")
}

// Clean task for nativeAndroidX86Jar
tasks.register('cleanNativeAndroidX86Jar', Delete) {
    delete layout.buildDirectory.file("libs/jlibtorrent-android-x86-${version}.jar")
}

// Clean task for nativeAndroidArm64Jar
tasks.register('cleanNativeAndroidArm64Jar', Delete) {
    delete layout.buildDirectory.file("libs/jlibtorrent-android-arm64-${version}.jar")
}

// Clean task for nativeAndroidX64Jar
tasks.register('cleanNativeAndroidX64Jar', Delete) {
    delete layout.buildDirectory.file("libs/jlibtorrent-android-x86_64-${version}.jar")
}

tasks.named('assemble').configure {
    dependsOn(
            tasks.named('nativeMacOSArm64Jar'),
            tasks.named('nativeMacOSX86_64Jar'),
            tasks.named('nativeWindowsX86_64Jar'),
            tasks.named('nativeLinuxX86_64Jar'),
            tasks.named('nativeLinuxArm64Jar'),
            tasks.named('nativeAndroidArmJar'),
            tasks.named('nativeAndroidX86Jar'),
            tasks.named('nativeAndroidArm64Jar'),
            tasks.named('nativeAndroidX64Jar')
    )
}


// Reusable POM configuration method
def configurePom(MavenPom pom, String artifactName, String desc) {
    pom.name = artifactName
    pom.description = desc
    pom.url = 'https://github.com/frostwire/frostwire-jlibtorrent'
    pom.scm {
        connection = 'scm:git:git://github.com/frostwire/frostwire-jlibtorrent.git'
        developerConnection = 'scm:git:ssh:git@github.com/frostwire/frostwire-jlibtorrent.git'
        url = 'https://github.com/frostwire/frostwire-jlibtorrent'
    }
    pom.licenses {
        license {
            name = 'The MIT License'
            url = 'https://github.com/frostwire/frostwire-jlibtorrent/blob/master/LICENSE.md'
        }
    }
    pom.developers {
        developer {
            id = 'gubatron'
            name = 'Angel Leon'
            email = 'gubatron@gmail.com'
        }
    }
}

// Maven publishing to GitHub Packages
publishing {
    repositories {
        maven {
            name = 'GitHubPackages'
            url = "https://maven.pkg.github.com/${System.getenv('GITHUB_REPOSITORY') ?: 'frostwire/frostwire-jlibtorrent'}"
            credentials {
                username = System.getenv('USERNAME')
                // github.actor -> defined in publish.yml when publish action is invoked
                password = System.getenv('TOKEN')
                // secrets.GITHUB_TOKEN -> generated automatically when a github action is ran, has package:write permissions
            }
        }
    }
    publications {
        // Platform-independent jlibtorrent JAR
        jlibtorrent(MavenPublication) {
            groupId = project.group
            artifactId = 'jlibtorrent'
            version = project.version
            artifact file("$buildDir/libs/jlibtorrent-${version}.jar")
            artifact(file("$buildDir/libs/jlibtorrent-${version}-sources.jar")) {
                classifier = 'sources'
            }
            artifact(file("$buildDir/libs/jlibtorrent-${version}-javadoc.jar")) {
                classifier = 'javadoc'
            }
            pom {
                configurePom(delegate, 'frostwire-jlibtorrent', 'The swig Java interface for libtorrent by the makers of FrostWire. Contains only .class files to be used in any architecture alongside the native binary jar')
            }
        }
        // macOS ARM64
        macOSArm64(MavenPublication) {
            groupId = project.group
            artifactId = 'jlibtorrent-macosx-arm64'
            version = project.version
            artifact file("$buildDir/libs/jlibtorrent-macosx-arm64-${version}.jar")  // Built on macOS ARM64 with swig/build tasks and ./gradlew nativeMacOSArm64Jar
            pom {
                configurePom(delegate, 'frostwire-jlibtorrent-macosx-arm64', 'Native macOS ARM64 binaries for jlibtorrent.')
            }
        }
        // macOS x86_64
        macOSX86_64(MavenPublication) {
            groupId = project.group
            artifactId = 'jlibtorrent-macosx-x86_64'
            version = project.version
            artifact file("$buildDir/libs/jlibtorrent-macosx-x86_64-${version}.jar")  // Built on macOS x86_64 with swig/build tasks and ./gradlew nativeMacOSX86_64Jar
            pom {
                configurePom(delegate, 'frostwire-jlibtorrent-macosx-x86_64', 'Native macOS x86_64 binaries for jlibtorrent.')
            }
        }
        // Windows
        windows(MavenPublication) {
            groupId = project.group
            artifactId = 'jlibtorrent-windows'
            version = project.version
            artifact file("$buildDir/libs/jlibtorrent-windows-${version}.jar")  // Built in Docker with swig/build tasks and ./gradlew nativeWindowsX86_64Jar
            pom {
                configurePom(delegate, 'frostwire-jlibtorrent-windows', 'Native Windows binaries for jlibtorrent.')
            }
        }
        // Linux x86_64
        linuxX86_64(MavenPublication) {
            groupId = project.group
            artifactId = 'jlibtorrent-linux-x86_64'
            version = project.version
            artifact file("$buildDir/libs/jlibtorrent-linux-x86_64-${version}.jar")  // Built in Docker with swig/build tasks and ./gradlew nativeLinuxX86_64Jar
            pom {
                configurePom(delegate, 'frostwire-jlibtorrent-linux-x86_64', 'Native Linux x86_64 binaries for jlibtorrent.')
            }
        }
        // Linux ARM64
        linuxArm64(MavenPublication) {
            groupId = project.group
            artifactId = 'jlibtorrent-linux-arm64'
            version = project.version
            artifact file("$buildDir/libs/jlibtorrent-linux-arm64-${version}.jar")  // Built in Docker with swig/build tasks and ./gradlew nativeLinuxArm64Jar
            pom {
                configurePom(delegate, 'frostwire-jlibtorrent-linux-arm64', 'Native Linux ARM64 binaries for jlibtorrent.')
            }
        }
        // Android ARM
        androidArm(MavenPublication) {
            groupId = project.group
            artifactId = 'jlibtorrent-android-arm'
            version = project.version
            artifact file("$buildDir/libs/jlibtorrent-android-arm-${version}.jar")  // Built in Docker with swig/build tasks and ./gradlew nativeAndroidArmJar
            pom {
                configurePom(delegate, 'frostwire-jlibtorrent-android-arm', 'Native Android ARM binaries for jlibtorrent.')
            }
        }
        // Android x86
        androidX86(MavenPublication) {
            groupId = project.group
            artifactId = 'jlibtorrent-android-x86'
            version = project.version
            artifact file("$buildDir/libs/jlibtorrent-android-x86-${version}.jar")  // Built in Docker with swig/build tasks and ./gradlew nativeAndroidX86Jar
            pom {
                configurePom(delegate, 'frostwire-jlibtorrent-android-x86', 'Native Android x86 binaries for jlibtorrent.')
            }
        }
        // Android ARM64
        androidArm64(MavenPublication) {
            groupId = project.group
            artifactId = 'jlibtorrent-android-arm64'
            version = project.version
            artifact file("$buildDir/libs/jlibtorrent-android-arm64-${version}.jar")  // Built in Docker with swig/build tasks and ./gradlew nativeAndroidArm64Jar
            pom {
                configurePom(delegate, 'frostwire-jlibtorrent-android-arm64', 'Native Android ARM64 binaries for jlibtorrent.')
            }
        }
        // Android x86_64
        androidX64(MavenPublication) {
            groupId = project.group
            artifactId = 'jlibtorrent-android-x86_64'
            version = project.version
            artifact file("$buildDir/libs/jlibtorrent-android-x86_64-${version}.jar")  // Built in Docker with swig/build tasks and ./gradlew nativeAndroidX64Jar
            pom {
                configurePom(delegate, 'frostwire-jlibtorrent-android-x86_64', 'Native Android x86_64 binaries for jlibtorrent.')
            }
        }
    } // publications
} // publishing
