apply plugin: TaBuildPlugin

configurations {
    defaultConfig {
        description 'Compile Tiger Trustlet'
    }
}

def getTaVersionFile() {
    return new File('TigerTaV4/src/TigerVersion.c')
}

def getTaDeviceConfig() {
    return new File('TigerTaV4/src/TigerDeviceConfig.c')
}


def getLLVMPath() {
    def llvm = null
    switch (TIGER_CHIP_NAME) {
        case 'MSM8953':
        case 'MSM8976':
        case 'MSM8996':
            if (!project.hasProperty('LLVM_3524_PATH')) {
                throw new GradleException("Please set LLVM_3524_PATH in gradle.properties file.\n" +
                        "Example: LLVM_3524_PATH=/toolchains/Qualcomm/llvm/3.5.2.4")
            }
            llvm = LLVM_3524_PATH
            break
        case 'MSM8998':
        case 'SDM660':
        case 'SDM450':
            if (!project.hasProperty('LLVM_374_PATH')) {
                throw new GradleException("Please set LLVM_374_PATH in gradle.properties file.\n" +
                        "Example: LLVM_374_PATH=/toolchains/Qualcomm/llvm/3.7.4")
            }

            llvm = LLVM_374_PATH
            break
        case 'SDM845':
            if (!project.hasProperty('LLVM_396_PATH')) {
                throw new GradleException("Please set LLVM_396_PATH in gradle.properties file.\n" +
                        "Example: LLVM_396_PATH=/toolchains/Qualcomm/llvm/3.9.6")
            }

            llvm = LLVM_396_PATH
            break
        case 'SM8150':
            if (!project.hasProperty('LLVM_399_PATH')) {
                throw new GradleException("Please set LLVM_399_PATH in gradle.properties file.\n" +
                        "Example: LLVM_399_PATH=/toolchains/Qualcomm/llvm/3.9.9")
            }

            llvm = LLVM_399_PATH
            break
        case 'SDM710':
            if (!project.hasProperty('LLVM_403_PATH')) {
                throw new GradleException("Please set LLVM_403_PATH in gradle.properties file.\n" +
                        "Example: LLVM_403_PATH=/toolchains/Qualcomm/llvm/4.0.3")
            }

            llvm = LLVM_403_PATH
            break
        default:
            throw new GradleException("Please choose llvm version in getLLVMPath().")
            break
    }

    return llvm
}


String getTzAbi() {
    def TZ_ABI = ""
    if ("arm64-v8a" == TIGER_ABI) {
        TZ_ABI = "ARM64"
    }
    return TZ_ABI
}


//check directly build avaliable or not ???
def getQseeBuildString(boolean cleanOption, boolean signOption) {
    def clean = "";
    if (cleanOption == true) {
        clean = '-c'
    }

    def sign = "";
    if (signOption == true) {
        sign = 'SIGN'
    }
    String scriptPath = getPath('TIGER_COMBINATION_PATH')
    String productName = ''
    String chipset = "CHIPSET="
    switch (TIGER_CHIP_NAME) {
        case 'MSM8953':
        case 'MSM8976':
        case 'MSM8996':
        return 'bash'.split(' ') +
                ((projectDir.absolutePath + "/../BuildScripts/qcom_build/build.sh").split(' ') +
                 TIGER_CHIP_NAME.split(' ') + getTzAbi() + sign.split(' ')) as List
            break
        case 'MSM8998':
            scriptPath += "/nhlos/trustzone_images/build/ms"
            chipset += "msm8998"
            break
        case 'SDM845':
            scriptPath += "/nhlos/trustzone_images/build/ms"
            chipset += "sdm845"
            break
        case 'SDM660':
            scriptPath += "/nhlos/TZ.BF.4.0.7/trustzone_images/build/ms"
            productName = "PRODUCT_NAME=jackpotqlte_chn_open"
            chipset += "sdm660"
            break
        case 'SDM450':
            scriptPath += "/nhlos/TZ.BF.4.0.7/trustzone_images/build/ms"
            productName = "PRODUCT_NAME=j8plusqlte_chn_open"
            chipset += "sdm450"
            break
        default:
            throw new GradleException("Please specify 'TIGER_CHIP_NAME' in build command")
    }
    return 'python'.split(' ') +
           (scriptPath + "/build_all.py").split(' ') +
           ("-b TZ.BF.4.0").split(' ') +
           productName +
           chipset +
           ("tigerfp").split(' ') +
           clean.split(' ') as List
}

/*
task copySrcToNhlos(type: Copy) {
    def tigerfpNhlos = getPath('TIGER_COMBINATION_PATH')

    switch (TIGER_CHIP_NAME) {
        case 'MSM8953':
        case 'MSM8976':
        case 'MSM8996':
        case 'MSM8998':
        case 'SDM845':
        case 'SDM450':
        case 'SDM710':
        case 'SDM660':
            tigerfpNhlos += '/trustzone_images/core/securemsm/trustzone/qsapps/tigerfp'
            break
        default:
            throw new GradleException("Please specify 'TIGER_CHIP_NAME' in build command")
    }

    from projectDir.absolutePath
    into tigerfpNhlos
    include 'include/**'
    include 'tests/**'
    include 'src/**'
}
*/

task build(type: Exec) {
    description 'Build TigerTa project'

    environment.put("LLVM_PATH", getLLVMPath())
    environment.put("LINARO_AARCH64_PATH", LINARO_AARCH64_PATH)
    environment.put("LINARO_AARCH32_PATH", LINARO_AARCH32_PATH)
    environment.put('TIGER_COMBINATION_PATH', getPath('TIGER_COMBINATION_PATH'))
    environment.put("TIGER_CHIP_NAME", TIGER_CHIP_NAME)

    if (project.hasProperty('TIGER_MODE')) {
        environment.put("TIGER_MODE", TIGER_MODE)
    }

    // New build type env
    environment.put('TIGER_LOCAL_BUILD', 'true')
    environment.put('TIGER_VERSION', '2')

    if (getTzModel() == "QCOM") {
        // TODO(o.kachkan): move to function like  checkGradleBlowfishProperties() and set env variable in it
        // Set the environment variables to use for the process.
        environment.put("LLVM_PATH", getLLVMPath())
        environment.put("LINARO_AARCH64_PATH", LINARO_AARCH64_PATH)
        environment.put("LINARO_AARCH32_PATH", LINARO_AARCH32_PATH)
        environment.put("TIGER_ABI", getTzAbi())

        if (project.hasProperty('TIGER_BUILD_TESTS')) {
            environment.put("TIGER_BUILD_TESTS", 'true')
        }

        //commandLine getQseeBuildString(false, false)
	commandLine 'bash'.split(' ') +
                ((projectDir.absolutePath + "/../BuildScripts/qcom_build/build.sh").split(' ') +
                        TIGER_CHIP_NAME.split(' ') + getTzAbi()) as List

    } else if (getTzModel() == 'BLOWFISH') {
        // Set the environment variables to use for the process.
        checkGradleBlowfishProperties()

        environment.put('TIGER_BLOWFISH_SDK_PATH', TIGER_BLOWFISH_SDK_PATH)

        def BLOWFISH_SW_TOOLCHAIN_PATH = "$TIGER_BLOWFISH_SDK_PATH/toolchains/arm-secureos-gnueabi-5.2-linux_x86"
        def BLOWFISH_SWD_PATH = "$TIGER_BLOWFISH_SDK_PATH/platforms/BF-2.0/swd"
        commandLine 'make', 'all',
                '--file=' + projectDir.absolutePath + "/buildScripts/blowfish/Makefile",
                'BLOWFISH_TRUSTLET_UUID=' + BLOWFISH_TRUSTLET_UUID,
                'BLOWFISH_SW_TOOLCHAIN_PATH=' + BLOWFISH_SW_TOOLCHAIN_PATH,
                'BLOWFISH_SWD_PATH=' + BLOWFISH_SWD_PATH,
                "TIGER_BUILD_TESTS=" + project.hasProperty("TIGER_BUILD_TESTS"),
                "TIGER_MODE=" + TIGER_MODE
    }
}

//task signTa(type: Exec) {
task signTa() {
/*
    description "Sign Tiger trustlet using Samsung's sign server"

    environment.put("LLVM_PATH", getLLVMPath())
    environment.put("LINARO_AARCH64_PATH", LINARO_AARCH64_PATH)
    environment.put("LINARO_AARCH32_PATH", LINARO_AARCH32_PATH)
    environment.put('TIGER_COMBINATION_PATH', getPath('TIGER_COMBINATION_PATH'))
    environment.put("TIGER_CHIP_NAME", TIGER_CHIP_NAME)

    // New build type env
    environment.put('TIGER_LOCAL_BUILD', 'true')
    environment.put('TIGER_VERSION', '2')

    if (project.hasProperty('TIGER_MODE')) {
        environment.put("TIGER_MODE", TIGER_MODE)
    }

    if (project.hasProperty('TIGER_BUILD_TESTS')) {
        environment.put("TIGER_BUILD_TESTS", 'true')
    }

    environment.put("TIGER_SIGN_TA", "true")
    environment.put("TIGER_SIGN_OUT_PATH", projectDir.absolutePath + "/../BuildScripts/qcom_build/out")

    // run bash script to build TA
    if (TIGER_TZ_MODEL == "QCOM") {
        commandLine 'bash'.split(' ') +
                ((projectDir.absolutePath + "/../BuildScripts/qcom_build/build.sh").split(' ') +
                        ("SIGN").split(' ') + TIGER_CHIP_NAME.split(' ') + getTzAbi()) as List

    } else if (getTzModel() == 'BLOWFISH') {
        checkGradleBlowfishProperties()
        environment.put('TIGER_BLOWFISH_SDK_PATH', TIGER_BLOWFISH_SDK_PATH)
        dependsOn += build
        def BLOWFISH_TA_PATH = project.projectDir.absolutePath + "/buildScripts/blowfish"
        def UNSIGNED_TA = BLOWFISH_TA_PATH + "/build/unsigned_" + BLOWFISH_TRUSTLET_UUID
        def SIGNED_TA = BLOWFISH_TA_PATH + "/build/" + BLOWFISH_TRUSTLET_UUID
        commandLine 'java', "-jar", BLOWFISH_SIGN_CLIENT_PATH,
                "-model", "BF_SAMSUNG_DRV",
                "-runtype", "ss_bf_ta",
                "-input", "${UNSIGNED_TA}",
                "-output", "${SIGNED_TA}"
    }
*/
}

task doSign(type: Exec) {
    description "sign and split TA"

    environment.put('TIGER_COMBINATION_PATH', getPath('TIGER_COMBINATION_PATH'))
    environment.put("TIGER_CHIP_NAME", TIGER_CHIP_NAME)

    if (getTzModel() == "QCOM") {
        commandLine 'bash', projectDir.absolutePath + "/../BuildScripts/qcom_build/tools/SignAndSplit.sh"
    } else if (getTzModel() == 'BLOWFISH') {
        checkGradleBlowfishProperties()
        environment.put('TIGER_BLOWFISH_SDK_PATH', TIGER_BLOWFISH_SDK_PATH)
        dependsOn += build
        def BLOWFISH_TA_PATH = project.projectDir.absolutePath + "/buildScripts/blowfish"
        def UNSIGNED_TA = BLOWFISH_TA_PATH + "/build/unsigned_" + BLOWFISH_TRUSTLET_UUID
        def SIGNED_TA = BLOWFISH_TA_PATH + "/build/" + BLOWFISH_TRUSTLET_UUID
        commandLine 'java', "-jar", BLOWFISH_SIGN_CLIENT_PATH,
                "-model", "BF_SAMSUNG_DRV",
                "-runtype", "ss_bf_ta",
                "-input", "${UNSIGNED_TA}",
                "-output", "${SIGNED_TA}"
    }
}

task pushTa(type: Exec) {
    description "Push tiger Trustlet to device"
    if (getTzModel() == "QCOM") {
        commandLine 'bash', projectDir.absolutePath + "/../BuildScripts/qcom_build/upload.sh"
    } else if (getTzModel() == 'BLOWFISH') {
        def SIGNED_TA = project.projectDir.absolutePath + "/buildScripts/blowfish" + "/build/" + BLOWFISH_TRUSTLET_UUID

        commandLine 'adb', 'push', "$SIGNED_TA", "/system/tee/" + "$BLOWFISH_TRUSTLET_UUID"
    }
}

task clean(type: Delete) {
    description 'Clean TigerTa project'
    // Delete all generated files and directories
    doFirst {
        new File(projectDir, '../BuildScripts/qcom_build/out').deleteDir()
        new File(projectDir, 'buildScripts/blowfish/build').deleteDir()
        getTaVersionFile().delete()
        if (TIGER_CHIP_NAME != 'MT6757') {
            //exec {
            //    environment.put('TIGER_COMBINATION_PATH', getPath('TIGER_COMBINATION_PATH'))
            //    if (project.hasProperty('TIGER_MODE')) {
            //        environment.put("TIGER_MODE", TIGER_MODE)
            //    }
            //    // New build type env
            //    environment.put('TIGER_LOCAL_BUILD', 'true')
            //    environment.put('TIGER_VERSION', '1')
                //commandLine getQseeBuildString(true, false)
            //}
        }
    }
}

def getGitHash = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'describe'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

task createVersionFile() << {
    //description 'Generate git-based version source file.'

    //def stdout = new ByteArrayOutputStream()
    //exec {
    //    commandLine 'git', 'describe'
    //    standardOutput = stdout
    //    ignoreExitValue true
    //}

    //def codeString = "const char* tigerAppVersion = \"" + "2.1.9" + "\";\n";
    //getTaVersionFile().write(codeString)
}

task createDeviceConfigFile() << {
    description 'Generate device configuration.'

    def tzModelName, tzModelVersion, phyAddr, fingerprintSensorName, fingerprintSensorVersion
    def codeString = ""

    if (getTzModel() == 'BLOWFISH') {
        (tzModelName, tzModelVersion, phyAddr, fingerprintSensorName, fingerprintSensorVersion) = getDeviceConfig()
        codeString += "#include <stdint.h>\n"
    } else {
        (tzModelName, tzModelVersion, fingerprintSensorName, fingerprintSensorVersion) = getDeviceConfig()
    }

    codeString += \
        "const char* TEE_NAME = \"" + "$tzModelName" + "\";\n" +
        "const char* TEE_VERSION = \"" + "$tzModelVersion" + "\";\n" +
        "const char* FINGERPRINT_SENSOR_NAME = \"" + "$fingerprintSensorName" + "\";\n" +
        "const char* FINGERPRINT_SENSOR_VERSION = \"" + "$fingerprintSensorVersion" + "\";\n";
//        "const char* FINGERPRINT_AUTH_TA_NAME = \"" + "$fpAuthTaName" + "\";\n";

    if (getTzModel() == 'BLOWFISH') {
        codeString += "const uintptr_t PHY_ADDR = (uintptr_t) $phyAddr;\n";
    }

    getTaDeviceConfig().write(codeString)
}

def checkGradleBlowfishProperties() {
    if (!project.hasProperty('BLOWFISH_TRUSTLET_UUID')) {
        throw new GradleException("Please set BLOWFISH_TRUSTLET_UUID in gradle.properties file.\n" +
                "Example: BLOWFISH_TRUSTLET_UUID=00000000-0000-0000-0000-544947455246")
    }
    if (!project.hasProperty('BLOWFISH_SIGN_CLIENT_PATH')) {
        throw new GradleException("Please set full path to the sign client in gradle.properties file.\n" +
                "Example: BLOWFISH_SIGN_CLIENT_PATH=/home/kvolobuyev/Perforce/SRK_ASL_KVolobuyev_C10/NILE/Cinnamon/buildscript/tools/signclient.jar")
    }
    if (!project.hasProperty('TIGER_BLOWFISH_SDK_PATH')) {
        throw new GradleException("Please set full path to the SDK folder in gradle.properties file.\n" +
                "Example: TIGER_BLOWFISH_SDK_PATH=/home/kvolobuyev/Soft/bf_sdk")
    }
}


//project.tasks.build.dependsOn project.tasks.copySrcToNhlos

//project.tasks.copySrcToNhlos.dependsOn project.tasks.createDeviceConfigFile
//project.tasks.copySrcToNhlos.dependsOn project.tasks.createVersionFile


project.tasks.build.dependsOn project.tasks.createDeviceConfigFile

project.tasks.signTa.dependsOn project.tasks.build
project.tasks.signTa.dependsOn project.tasks.doSign

project.tasks.pushTa.dependsOn project.rootProject.tasks.remountSystem
//project.tasks.signTa.dependsOn project.tasks.build
