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().substring(1)
}

repositories {
    jcenter()
}

dependencies {
    compile 'com.android.support:support-v4:24.2.0'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:support-annotations:24.2.0'

    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:1.2.1'
    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.0') {
        exclude module: 'support-v4'
        exclude module: 'support-annotations'
    }
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'io.reactivex:rxandroid:0.23.0'

    testCompile 'junit:junit:4.12'

    testCompile "org.robolectric:robolectric:3.1.2"

    testCompile "org.mockito:mockito-core:1.10.19"

    androidTestCompile 'com.android.support:support-annotations:24.2.0'
    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:98e71bd00a713b9f848abbae4874601533aaf8492bf9b508e14d07f844a53839',
                'commons-io:commons-io:a10418348d234968600ccb1d988efcbbd08716e1d96936ccc1880e7d22513474',
                'commons-net:commons-net:c25b0da668b3c5649f002d504def22d1b4cb30d206f05428d2fe168fa1a901c2',
                'com.android.support:animated-vector-drawable:af39eb9a350084eae2a9e119db762633bbf1ad25eed5305dcc3af2411442ba68',
                'com.android.support:appcompat-v7:29b1e21852ace88ad406bbe32d7791b518118f0a61a61453aca0affa8ef909e0',
                'com.android.support:support-annotations:af5868da6750bdf42aec5d85fa87ac30de2b72939ca80437a6247e5753a07cad',
                'com.android.support:support-compat:de70ac981118229b70ca29961b6df510d6f498c0ececd1e11e19a8073d1580c9',
                'com.android.support:support-core-ui:6cd8723abdeafbd8d05816d7b4a307dd4dbebba9cb145f98e12834ab3ebd9212',
                'com.android.support:support-core-utils:20dd25988a360df5887e8ad5d9cf9b77b54fb014a17163f2125ecde8aa635846',
                'com.android.support:support-fragment:50aa9d408d33b82acda71423ce2980e54186caaae50f689ecd90e6692dcc3ed4',
                'com.android.support:support-media-compat:b6b4ed6dd8e0678bb5fd6457ea9155766cc12d5bc5df9c283c01e0dc782ffb19',
                'com.android.support:support-v4:989888d1b48badd790b8386e9ab61ec793a453ce782faa11e89634d889db3a44',
                'com.android.support:support-vector-drawable:049b53487c07d6270f4b85896c0871645cfb2c6300bbd83f7e5ebf91f069d6a4',
                'com.google.zxing:core:b4d82452e7a6bf6ec2698904b332431717ed8f9a850224f295aec89de80f2259',
                '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:611ec5bde9d799fd57e1efec5c375f9f460de2cdda98918541decc9a7d02f2ad',
                '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
        }
    }
}

android {
    compileSdkVersion 24
    buildToolsVersion '24.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
    }

    defaultConfig {
        versionCode 101006
        versionName getVersionName()
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    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
                }
            }
        }
    }

    lintOptions {
        checkReleaseBuilds false
        abortOnError true

        htmlReport true
        xmlReport false
        textReport false

        // Our translations are crowd-sourced
        disable 'MissingTranslation'

        // to make CI fail on errors until this is fixed https://github.com/rtyley/spongycastle/issues/7
        warning 'InvalidPackage'
    }

    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.1'
}

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'
    }
}