apply from: "../private/env.gradle"

import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import java.nio.file.Files
import java.security.MessageDigest


def getGitHash = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', '--short', 'HEAD'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

ext{
    JEK_FILE_DECRYPTED = rootProject.file("private/myapp.jks")
    GIT_COMMIT_ID = getGitHash()
}


static def checkEmpty(String... str) {
    if (str == null) {
        return true
    }
    for (String s : str) {
        if (s == null || s.isEmpty()) {
            return true
        }
    }
    return false
}

task releaseSigningConfigs {

    println("-----releaseSigningConfigs----")
    def jksPwd = project.myEnv.JKS_PWD
    if (checkEmpty(jksPwd,project.myEnv.JKS_FILE)) {
        println("sign config error!!")
        return
    }

    try {
        def cipher = Cipher.getInstance("AES")
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(jksPwd.getBytes(), "AES"))

        def bytes = cipher.doFinal(file(rootProject.file(project.myEnv.JKS_FILE)).bytes)

        JEK_FILE_DECRYPTED.withOutputStream {
            it.write(bytes)
        }

    } catch (Throwable throwable) {
        throwable.printStackTrace()
    }
}


task pushApkFile {

    doLast {

        println("-----pushApkFile----")

        def server = project.myEnv.P_FILE_SERVER
        def pwd = project.myEnv.P_SERVER_PWD
        def auth = project.myEnv.P_SERVER_AUTH
        if (checkEmpty(server, pwd, auth)) {
            println("config error!!")
            return
        }
        def sourceApk = project.file("build/outputs/apk/release/app-release.apk")

        if (!sourceApk.exists()) {
            println("release apk not found !")
            return
        }

        def apk = project.file("appopsx-v${VERSION_NAME}-${new Date().format("yyyyMMdd")}-${GIT_COMMIT_ID}.apk")

        Files.copy(sourceApk.toPath(), apk.toPath())


        apk.newInputStream().withStream {
            MessageDigest digest = MessageDigest.getInstance("MD5")
            byte[] buff = new byte[1024 * 256]
            int l = -1
            while ((l = it.read(buff, 0, buff.length)) != -1) {
                digest.update(buff, 0, l)
            }
            def checksum = new BigInteger(1, digest.digest()).toString(16).padLeft(32, "0")
            println("${apk} md5:" + checksum)
        }

        String CRLF = "\r\n";

        HttpURLConnection connection = new URL(server).openConnection()
        connection.setRequestMethod("POST")
        connection.setDoInput(true)
        connection.setDoOutput(true)
        String boundary = "------------${Long.toHexString(System.nanoTime())}${Integer.toHexString(thisObject.hashCode())}"

        connection.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary.substring(2))

        def text = new StringBuilder(boundary).append(CRLF)
                .append("Content-Disposition: form-data; name=\"pwd\"").append(CRLF)
                .append("Content-Type: text/plain; charset=utf-8").append(CRLF)
                .append(CRLF)
                .append(pwd)
                .append(CRLF)
                .append(boundary)
                .append(CRLF)
                .append("Content-Disposition: form-data; name=\"file\"; filename=\"" + apk.getName() + "\"").append(CRLF)
                .append("Content-Type: application/vnd.android.package-archive").append(CRLF)
                .append("Content-Transfer-Encoding: binary").append(CRLF)
                .append(CRLF).toString().bytes

        def end = (CRLF + boundary + "--" + CRLF).toString().bytes

        connection.addRequestProperty("Authorization", "Basic " + auth.bytes.encodeBase64())

        connection.outputStream.write(text)
        connection.outputStream.flush()
        Files.copy(apk.toPath(), connection.outputStream)
        connection.outputStream.flush()
        connection.outputStream.write(end)
        connection.outputStream.flush()

        if (connection.responseCode == HttpURLConnection.HTTP_OK) {
            println("server success response: " + connection.inputStream.newReader().text)
        } else {
            println("server ERROR response: " + connection.errorStream.newReader().text)
        }
        connection.disconnect()
    }

}

task releaseResource{
    doLast{
        JEK_FILE_DECRYPTED.delete()
    }
}

tasks.whenTaskAdded { task ->
    println("$task.name")
    if (task.name == "assembleRelease") {
        task.finalizedBy(pushApkFile,releaseResource)
    }
}
