def version = '1.3.10'
def versionNum = 9000020
def webInstallDir = "${project.buildDir}/web"

buildscript {
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.2'
    }
}

repositories {
    google()
    mavenCentral()
}

apply plugin: 'com.android.application'

android {
    dataBinding.enabled true
    externalNativeBuild.cmake.path 'CMakeLists.txt'

    defaultConfig {
        applicationId 'com.ap.transmission.btc'
        minSdkVersion 19
        targetSdkVersion 30
        compileSdkVersion 30
        versionCode versionNum
        versionName version

        externalNativeBuild.cmake {
            targets 'transmissionbtc'
            arguments "-DTR_SRC_DIR=${project.buildDir}/transmission", "-DTR_WEB_INSTALL_DIR=${webInstallDir}"
        }

        ndk {
            def abi = project.properties['ABI']
            def filters = (abi != null) ? abi.split(",") : ['arm64-v8a', 'armeabi-v7a', 'x86', 'x86_64']
            debugSymbolLevel 'FULL'
            abiFilters = filters
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }

    def localPropsFile = file('local.properties')

    if (localPropsFile.isFile()) {
        def localProps = new Properties()
        localProps.load(localPropsFile.newDataInputStream())

        if (localProps['kestorePath'] != null) {
            signingConfigs {
                release {
                    storeFile file(localProps["kestorePath"])
                    storePassword localProps["kestorePassword"]
                    keyAlias localProps["kestoreAlias"]
                    keyPassword localProps["kestoreKeyPassword"]
                }
            }
        }
    }

    sourceSets {
        main {
            assets.srcDirs += "${project.buildDir}/assets"
        }
    }

    buildTypes {
        release {
            debuggable false
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }

        debug {
            debuggable true
            applicationIdSuffix '.debug'
            signingConfig signingConfigs.release
        }
    }

    applicationVariants.all { v ->
        tasks["merge${v.name.capitalize()}Assets"].dependsOn("mergeWebAssets${v.name.capitalize()}")
        tasks["mergeWebAssets${v.name.capitalize()}"].dependsOn("externalNativeBuild${v.name.capitalize()}")
    }

    lintOptions {
        disable 'MissingTranslation'
    }
}

dependencies {
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

task cleanAll(type: Delete) {
    delete project.buildDir
    delete file(".cxx")
}

task mergeWebAssets() {
    doLast {
        def webDir = "${project.buildDir}/assets/web"
        def arch = file("${project.buildDir}/web-control.tar.gz")

        if (!arch.isFile()) {
            def url = new URL('https://github.com/ronggang/transmission-web-control/archive/master.tar.gz')
            url.withInputStream { i -> arch.withOutputStream { it << i } }
        }

        def md = java.security.MessageDigest.getInstance("SHA1")
        arch.eachByte(1024 * 1024) { byte[] buf, int n -> md.update(buf, 0, n) }
        def sha1 = new BigInteger(1, md.digest()).toString(16).padLeft( 40, '0' )
        new File(webDir).mkdirs()
        new File(webDir, 'checksum.sha1').write(sha1)

        copy {
            from "${webInstallDir}/usr/local/share/transmission/public_html"
            into webDir
        }

        copy {
            from "${webDir}/index.html"
            into webDir
            rename 'index.html', 'index.original.html'
        }

        copy {
            from(tarTree(arch)) {
                include 'transmission-web-control-master/src/**'
                includeEmptyDirs = false
                eachFile { fcd ->
                    fcd.relativePath = new RelativePath(!fcd.isDirectory(),
                            (String[]) fcd.relativePath.segments.drop(2))
                }
            }

            into webDir
            rename 'index.html', 'index.webcontrol.html'
        }
    }
}

task mergeWebAssetsRelease(dependsOn: mergeWebAssets) {
}

task mergeWebAssetsDebug(dependsOn: mergeWebAssets) {
}
