apply plugin: 'com.android.application'
apply plugin: 'witness'
apply plugin: 'checkstyle'
apply plugin: 'pmd'

/* gets the version name from the latest Git tag, stripping the leading v off */
def getVersionName = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'describe', '--tags', '--always'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

repositories {
    jcenter()
    maven {
        url "https://jitpack.io"
    }
}

ext {
    supportLibVersion = '25.2.0'
}

dependencies {
    compile "com.android.support:support-v4:${supportLibVersion}"
    compile "com.android.support:appcompat-v7:${supportLibVersion}"
    compile "com.android.support:gridlayout-v7:${supportLibVersion}"
    compile "com.android.support:support-annotations:${supportLibVersion}"
    compile "com.android.support:recyclerview-v7:${supportLibVersion}"
    compile "com.android.support:cardview-v7:${supportLibVersion}"
    compile "com.android.support:design:${supportLibVersion}"
    compile "com.android.support:support-vector-drawable:${supportLibVersion}"
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile "com.android.support:palette-v7:${supportLibVersion}"

    compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.google.zxing:core:3.2.1'
    compile 'eu.chainfire:libsuperuser:1.0.0.201602271131'
    compile 'cc.mvdan.accesspoint:library:0.2.0'
    compile 'info.guardianproject.netcipher:netcipher:2.0.0-alpha1'
    compile 'commons-io:commons-io:2.5'
    compile 'commons-net:commons-net:3.5'
    compile 'org.openhab.jmdns:jmdns:3.4.2'
    compile 'ch.acra:acra:4.9.1'
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'io.reactivex:rxandroid:0.23.0'
    compile 'com.hannesdorfmann:adapterdelegates3:3.0.1'

    // Migrate this to upstream https://github.com/Ashok-Varma/BottomNavigation if PR #110 gets
    // accepted to drop the minSdk to 10.
    compile('com.github.pserwylo:BottomNavigation:1.5.0') {
        // These pull our explicit dependency on 25.2.0 up to 25.3.0 which is broken
        // (https://code.google.com/p/android/issues/detail?id=251302)
        exclude module: 'appcompat-v7'
        exclude module: 'design'
    }

    compile 'com.fasterxml.jackson.core:jackson-core:2.8.7'
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.8.7'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.8.7'

    testCompile "org.robolectric:robolectric:3.3.1"
    testCompile 'junit:junit:4.12'
    // As per https://github.com/robolectric/robolectric/issues/1932#issuecomment-219796474
    testCompile 'org.khronos:opengl-api:gl1.1-android-2.1_r1'
    testCompile "org.mockito:mockito-core:1.10.19"

    androidTestCompile "com.android.support:support-annotations:${supportLibVersion}"
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test:rules:0.5'
}

if (!hasProperty('sourceDeps')) {

    repositories {
        // This is here until we sort out all dependencies from mavenCentral/jcenter. Once all of
        // the dependencies below have been sorted out, this can be removed.
        flatDir {
            dirs 'libs/binaryDeps'
        }
    }

    dependencies {
        compile 'com.madgag.spongycastle:pkix:1.53.0.0'
        compile 'com.madgag.spongycastle:prov:1.53.0.0'
        compile 'com.madgag.spongycastle:core:1.53.0.0'

        // Upstream doesn't have a binary on mavenCentral/jcenter yet:
        // https://github.com/kolavar/android-support-v4-preferencefragment/issues/13
        compile(name: 'support-v4-preferencefragment-release', ext: 'aar')

        // Fork for F-Droid, including support for https. Not merged into upstream
        // yet (seems to be a little unsupported as of late), so not using mavenCentral/jcenter.
        compile(name: 'nanohttpd-2.1.0')

        // Upstream doesn't have a binary on mavenCentral, and it is an SVN repo on
        // Google Code.  We include this code directly in this repo, and have made
        // modifications that should be pushed to anyone who wants to maintain it.
        compile(name: 'zipsigner')
    }

    // Only do the libraries imported from maven repositories. Our own libraries
    // (like privileged-api-lib) and the prebuilt jars already checked into the
    // source code don't need to be here.
    // generate using: `gradle -q calculateChecksums | sort -V`
    dependencyVerification {
        verify = [
                'cc.mvdan.accesspoint:library:0837b38adb48b66bb1385adb6ade8ecce7002ad815c55abf13517c82193458ea',
                'ch.acra:acra:d2762968c448757a7d6acc9f141881d9632f664988e9723ece33b5f7c79f3bc9',
                'commons-io:commons-io:a10418348d234968600ccb1d988efcbbd08716e1d96936ccc1880e7d22513474',
                'commons-net:commons-net:c25b0da668b3c5649f002d504def22d1b4cb30d206f05428d2fe168fa1a901c2',
                'com.android.support.constraint:constraint-layout-solver:8c62525a9bc5cff5633a96cb9b32fffeccaf41b8841aa87fc22607070dea9b8d',
                'com.android.support.constraint:constraint-layout:b0c688cc2b7172608f8153a689d746da40f71e52d7e2fe2bfd9df2f92db77085',
                'com.android.support:animated-vector-drawable:d2d59a11809abe3e64535346f05c22437b458de115f06ea35021fd0714960213',
                'com.android.support:appcompat-v7:120f3ce6cac682d69e53d80ccfa9cee076f0f11ccbe56d4ccd72099a745e81f9',
                'com.android.support:cardview-v7:c8610b0c334e4438d7e1ac58fcf2ac891fb26bac662c8351cd6b345c8d7b7076',
                'com.android.support:design:bf92337c5d0931df50a0dcec81682186dc1fbcf14c2fa1c6d51976963379b64d',
                'com.android.support:gridlayout-v7:257ac1280f2b3cc3c0afca1cd4d4d2e0b923b92a76b61a9c09fc57e892da7360',
                'com.android.support:palette-v7:e0050715e0d06fabcc8721b0c2893545fb00be9d761a6ef59ae69101d2368551',
                'com.android.support:recyclerview-v7:d6ba2c3a6196cc464eb4d69756229523a46eef7804991e5a8cf2d6306dbff10c',
                'com.android.support:support-annotations:47a2a30eab487a490a8a8f16678007c3d2b6dcae1e09b0485a12bbf921200ec3',
                'com.android.support:support-compat:5a7b6e18903458e3a561df24033476518f998cd7ae1ed747c2874e0685b999c7',
                'com.android.support:support-core-ui:cf3c75fd9a1b1dcbb6042d610515cd79cd0d65d3efd272d2250727187e8ca2ed',
                'com.android.support:support-core-utils:e0561cc9d00ae125d9e1ad8985d4639e68ce8399ae973e91674e97faaf658243',
                'com.android.support:support-fragment:f12633dd4d418a4edeb5ecf3bf4393edd0770b1eaa5d1ee3078c5e7c174868fd',
                'com.android.support:support-media-compat:e9f820d08e6a5735cfdb2a7d81d3c86b4a31897ac1edaeb55c7de06bcb370343',
                'com.android.support:support-v4:cd030f875dc7ee73b58e17598f368a2e12824fb3ceb4ed515ed815a47160228c',
                'com.android.support:support-vector-drawable:d79752fd68db5a8f5c18125517dafb9e4d7b593c755d188986010e15edd62454',
                'com.android.support:transition:5a4adefb1b410b23ad62b4477bc612edc47d3dfc8efed488deb8223b70b510d7',
                'com.fasterxml.jackson.core:jackson-annotations:6b7802f6c22c09c4a92a2ebeb76e755c3c0a58dfbf419835fae470d89e469b86',
                'com.fasterxml.jackson.core:jackson-core:256ff34118ab292d1b4f3ee4d2c3e5e5f0f609d8e07c57e8ad1f51c46d4fbb46',
                'com.fasterxml.jackson.core:jackson-databind:4f74337b6d18664be0f5b15c6664b17aa3972c9c175092328b139b894ff66f19',
                'com.github.pserwylo:BottomNavigation:83d7941a7a8d21ba1a8a708cd683b1bb07c6cf898044dc92eadf18a7a7d54f90',
                'com.google.zxing:core:b4d82452e7a6bf6ec2698904b332431717ed8f9a850224f295aec89de80f2259',
                'com.hannesdorfmann:adapterdelegates3:1b20d099d6e7afe57aceca13b713b386959d94a247c3c06a7aeb65b866ece02f',
                'com.madgag.spongycastle:core:9b6b7ac856b91bcda2ede694eccd26cefb0bf0b09b89f13cda05b5da5ff68c6b',
                'com.madgag.spongycastle:pkix:6aba9b2210907a3d46dd3dcac782bb3424185290468d102d5207ebdc9796a905',
                'com.madgag.spongycastle:prov:029f26cd6b67c06ffa05702d426d472c141789001bcb15b7262ed86c868e5643',
                'com.nostra13.universalimageloader:universal-image-loader:dbd5197ffec3a8317533190870a7c00ff3750dd6a31241448c6a5522d51b65b4',
                'eu.chainfire:libsuperuser:018344ff19ee94d252c14b4a503ee8b519184db473a5af83513f5837c413b128',
                'info.guardianproject.netcipher:netcipher:eeeb5d0d95ccfe176b4296cbd71a9a24c6efb0bab5c4025a8c6bc36abdddfc75',
                'io.reactivex:rxandroid:35c1a90f8c1f499db3c1f3d608e1f191ac8afddb10c02dd91ef04c03a0a4bcda',
                'io.reactivex:rxjava:2c162afd78eba217cdfee78b60e85d3bfb667db61e12bc95e3cf2ddc5beeadf6',
                'org.openhab.jmdns:jmdns:7a4b34b5606bbd2aff7fdfe629edcb0416fccd367fb59a099f210b9aba4f0bce',
        ]
    }

} else {

    logger.info "Setting up *source* dependencies for F-Droid (because you passed in the -PsourceDeps argument to gradle while building)."

    dependencies {
        compile(project(':extern:support-v4-preferencefragment')) {
            exclude module: 'support-v4'
        }
        compile project(':extern:nanohttpd:core')
        compile project(':extern:zipsigner')
    }

    task binaryDeps(type: Copy, dependsOn: ':app:prepareReleaseDependencies') {

        enabled = project.hasProperty('sourceDeps')
        description = "Copies .jar and .aar files from subproject dependencies in extern/ to app/libs. Requires the sourceDeps property to be set (\"gradle -PsourceDeps binaryDeps\")"

        from('../extern/') {
            include 'support-v4-preferencefragment/build/outputs/aar/support-v4-preferencefragment-release.aar'
            include 'nanohttpd/core/build/libs/nanohttpd-2.1.0.jar'
            include 'zipsigner/build/libs/zipsigner.jar'
        }

        into 'libs/binaryDeps'
        includeEmptyDirs false

        eachFile { FileCopyDetails details ->
            // Don't copy to a sub folder such as libs/binaryDeps/Project/build/outputs/aar/project.aar, but
            // rather libs/binaryDeps/project.aar.
            details.path = details.name
        }
    }
}

def isCi = "true".equals(System.getenv("CI"))
def preDexEnabled = "true".equals(System.getProperty("pre-dex", "true"))

android {
    compileSdkVersion 24
    buildToolsVersion '25.0.2'
    useLibrary 'org.apache.http.legacy'

    buildTypes {
        // use proguard on debug too since we have unknowingly broken
        // release builds before.
        all {
            minifyEnabled true
            useProguard true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            testProguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro', 'src/androidTest/proguard-rules.pro'
        }
    }

    compileOptions {
        compileOptions.encoding = "UTF-8"

        // Use Java 1.7, requires minSdk 8
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    aaptOptions {
        cruncherEnabled = false
    }

    dexOptions {
        // Improve build server performance by allowing disabling of pre-dexing
        // see http://tools.android.com/tech-docs/new-build-system/tips#TOC-Improving-Build-Server-performance
        // Skip pre-dexing when running on CI or when disabled via -Dpre-dex=false.
        preDexLibraries = preDexEnabled && !isCi
    }

    defaultConfig {
        versionCode 1001000
        versionName getVersionName()
        applicationId 'org.fdroid.fdroid'
        resValue "string", "applicationId", applicationId
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        debug {
            applicationIdSuffix ".debug"
            resValue "string", "applicationId", defaultConfig.applicationId + applicationIdSuffix
            versionNameSuffix "-debug"
        }
    }

    /* set the debug versionCode based on DB verson and how many commits in the repo */
    applicationVariants.all { variant ->
        if (variant.buildType.isDebuggable()) {
            // default to a timestamp, in case anything fails later
            variant.mergedFlavor.versionCode = new Date().getTime() / 1000
            try {
                def stdout = new ByteArrayOutputStream()
                exec {
                    commandLine 'git', 'rev-list', '--first-parent', '--count', 'HEAD'
                    standardOutput = stdout
                }
                def commitCount = Integer.parseInt(stdout.toString().trim())
                stdout = new ByteArrayOutputStream()
                exec {
                    commandLine 'sed', '-n', 's,.*DB_VERSION *= *\\([0-9][0-9]*\\).*,\\1,p', 'src/main/java/org/fdroid/fdroid/data/DBHelper.java'
                    standardOutput = stdout
                }
                def dbVersion = Integer.parseInt(stdout.toString().trim())
                println 'Setting debug versionCode: ' + sprintf("%d%05d", [dbVersion, commitCount])
                variant.mergedFlavor.versionCode = Integer.parseInt(sprintf("%d%05d", [dbVersion, commitCount]))
            }
            catch (ignored) {
            }
        }
    }

    testOptions {
        unitTests {
            // prevent tests from dying on android.util.Log calls
            returnDefaultValues = true
            all {
                // All the usual Gradle options.
                testLogging {
                    events "skipped", "failed", "standardOut", "standardError"
                    showStandardStreams = true
                }
            }
        }
    }

    sourceSets {
        test {
            java.srcDirs += "$projectDir/src/testShared/java"
        }

        androidTest {
            java.srcDirs += "$projectDir/src/testShared/java"
        }
    }

    lintOptions {
        checkReleaseBuilds false
        abortOnError true

        htmlReport true
        xmlReport false
        textReport false

        lintConfig file("lint.xml")
    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/INDEX.LIST'
        exclude '.readme'
    }
}

checkstyle {
    toolVersion = '7.2'
}

task checkstyle(type: Checkstyle) {
    configFile file("${project.rootDir}/config/checkstyle/checkstyle.xml")
    source 'src/main/java', 'src/test/java', 'src/androidTest/java'
    include '**/*.java'

    classpath = files()
}

pmd {
    toolVersion = '5.5.1'
    consoleOutput = true
}

task pmdMain(type: Pmd) {
    dependsOn 'assembleDebug'
    ruleSetFiles = files("${project.rootDir}/config/pmd/rules.xml", "${project.rootDir}/config/pmd/rules-main.xml")
    ruleSets = [] // otherwise defaults clash with the list in rules.xml
    source 'src/main/java'
    include '**/*.java'
}

task pmdTest(type: Pmd) {
    dependsOn 'assembleDebug'
    ruleSetFiles = files("${project.rootDir}/config/pmd/rules.xml", "${project.rootDir}/config/pmd/rules-test.xml")
    ruleSets = [] // otherwise defaults clash with the list in rules.xml
    source 'src/test/java', 'src/androidTest/java'
    include '**/*.java'
}

task pmd(dependsOn: [pmdMain, pmdTest]) {}

// This person took the example code below from another blogpost online, however
// I lost the reference to it:
// http://stackoverflow.com/questions/23297562/gradle-javadoc-and-android-documentation
android.applicationVariants.all { variant ->

    task("generate${variant.name}Javadoc", type: Javadoc) {
        title = "$name $version API"
        description "Generates Javadoc for F-Droid."
        source = variant.javaCompile.source

        def sdkDir
        Properties properties = new Properties()
        File localProps = project.rootProject.file('local.properties')
        if (localProps.exists()) {
            properties.load(localProps.newDataInputStream())
            sdkDir = properties.getProperty('sdk.dir')
        } else {
            sdkDir = System.getenv('ANDROID_HOME')
        }
        if (!sdkDir) {
            throw new ProjectConfigurationException("Cannot find android sdk. Make sure sdk.dir is defined in local.properties or the environment variable ANDROID_HOME is set.", null)
        }

        ext.androidJar = "${sdkDir}/platforms/${android.compileSdkVersion}/android.jar"
        classpath = files(variant.javaCompile.classpath.files) + files(ext.androidJar)
        options.links("http://docs.oracle.com/javase/7/docs/api/");
        options.links("http://d.android.com/reference/");
        exclude '**/BuildConfig.java'
        exclude '**/R.java'
    }
}