buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:0.5.+"
    }
}

apply plugin: "android"

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 12
    buildToolsVersion "17"
}

def requireFileInDirectory(String directory, String file)
{
    if(fileTree(dir: directory, include: '**/'+file).isEmpty()) {
        throw new GradleException('Not found ' + file + ' in ' + directory + ' directory')
    }
}

def sdkCopyPkcs11()
{
    if(fileTree(dir: 'libs', include: '**/'+'librtpkcs11ecp.so').isEmpty() && !fileTree(dir: '../../../../../Libs/android/native/pkcs11-sm-cryptopro/', include: 'librtpkcs11ecp.so').isEmpty()) {
        copy {
            from fileTree(dir: '../../../../../Libs/android/native/pkcs11-sm-cryptopro/', include: 'librtpkcs11ecp.so')
            into 'libs/'
        }
    }
}

task extractJniDispatchFromJar {
    requireFileInDirectory('libs', 'android-arm.jar')
    FileTree tree = zipTree('libs/android-arm.jar')
    FileTree filtered = tree.matching {
        include 'libjnidispatch.so'
    }
    copy {
        from filtered
        into buildDir.getPath()+"/native-libs/"
    }
    
}

task prepareNativeLibs() {
    sdkCopyPkcs11()
    requireFileInDirectory('libs', 'librtpkcs11ecp.so')
    copy {
        from fileTree(dir: 'libs', include: '**/*.so')
        into buildDir.getPath()+'/native-libs/'
    }
}

task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs', dependsOn: ['prepareNativeLibs', 'extractJniDispatchFromJar']) {
    requireFileInDirectory(buildDir.getPath()+"/native-libs", 'libjnidispatch.so')
    requireFileInDirectory(buildDir.getPath()+"/native-libs", 'librtpkcs11ecp.so')
    destinationDir file(buildDir.getPath()+"/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: buildDir.getPath()+'/native-libs', include: '**/*.so')
    into 'lib/armeabi/'
}

task checkCryptoProBinaries() {
    ['JCP.jar', 'JCSP.jar', 'JInitCSP.jar', 'libsupport.so'].each { String item -> requireFileInDirectory("libs", item) }
}

tasks.withType(Compile) {
    compileTask -> compileTask.dependsOn(checkCryptoProBinaries, nativeLibsToJar)
}

dependencies {
    compile fileTree(dir: "libs", include: "*.jar")
}

dependencies {
    compile files("$buildDir/native-libs/native-libs.jar") {
        builtBy 'nativeLibsToJar'
    }
}
