package com.qmai.android.plugin.jg

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import java.io.ByteArrayOutputStream
import java.io.File
import javax.inject.Inject

open class JiaGuTask(): DefaultTask() {
    lateinit var apk: File
    lateinit var jiaGuPluginExtension: JiaGuPluginExtension
    //@Inject task的入口
    @Inject
    constructor(apk: File, jiaGuPluginExtension: JiaGuPluginExtension) : this() {
        group = "JiaGu"
        description = " 360 jiagu"
        this.apk = apk
        this.jiaGuPluginExtension = jiaGuPluginExtension
    }
    @TaskAction
    fun begin() {


        //判断jar文件是否存在
        val file = File(jiaGuPluginExtension.jiaGuToolsPath)
        if (!file.exists()){
            //创建父文件
            if (!file.parentFile.exists()) {
                file.parentFile.mkdirs()
            }
            println("path= ${jiaGuPluginExtension.jiaGuToolsPath}")
            //执行下载任务
            project.exec {
                it.commandLine("curl", "-o"
                        ,"${jiaGuPluginExtension.jiaGuToolsPath}",
                        "${jiaGuPluginExtension.jarDownloadUrl}")

            }
        }
        //判断apk是否存在
        val isExsit = apk.exists()
        print("apk isExsit = ${isExsit} ${if (isExsit) "apk path = ${apk.absolutePath} ${apk.name}" else ""}")

        //参照360加固文档编写相应的命令
        println("login 360 account")
        project.exec { execSpec ->
            execSpec.commandLine(
                    "java", "-jar", jiaGuPluginExtension.jiaGuToolsPath,
                    "-login", jiaGuPluginExtension.username, jiaGuPluginExtension.password
            )
        }
        println("import sign")
        project.exec { execSpec ->
            execSpec.commandLine(
                    "java",
                    "-jar",
                    jiaGuPluginExtension.jiaGuToolsPath,
                    "-importsign",
                    jiaGuPluginExtension.keyStoreFile,
                    jiaGuPluginExtension.keyStorePassword
                    ,
                    jiaGuPluginExtension.keyAlias,
                    jiaGuPluginExtension.keyAliasPassword
            )
        }

        jiaGuPluginExtension?.let {
            val filePath = apk.getParent()
            println("config ")
            project.exec { execSpec ->
                execSpec.commandLine("java", "-jar", jiaGuPluginExtension.jiaGuToolsPath,
                        "-jiagu", apk.getAbsolutePath(), filePath, "-autosign")

            }
        }
        println("origin apk.absolutePath:${apk.absolutePath}")
        println("source apk.absolutePath:${apk.parent}")

    }


    fun isInJenkins() :Boolean{
        val  map = System.getenv()
        if (map == null) {
            return false
        }
        var str = map.get("Path")
        if (str != null) {
            //it's windows
            return false
        } else {
            str = ""
            val it = map.iterator()
            while (it.hasNext()) {
                str += it.next()
            }
            return str.contains("jenkins")
        }
    }

    //获取当前分支
    fun getBranch():String {
        if (isInJenkins()) {
            return System.getenv().get("GIT_BRANCH").toString()
        } else {
            val byteOut =  ByteArrayOutputStream()
            project.exec {
                it.commandLine("git", "rev-parse", "--abbrev-ref", "HEAD")
                it.standardOutput = byteOut
            }
            val response =  String(byteOut.toByteArray())
            return response
        }

    }


}