/*
 * R3 Proprietary and Confidential
 *
 * Copyright (c) 2018 R3 Limited.  All rights reserved.
 *
 * The intellectual and technical concepts contained herein are proprietary to R3 and its suppliers and are protected by trade secret law.
 *
 * Distribution of this file or any portion thereof via any medium without the express permission of R3 is strictly prohibited.
 */

buildscript {
    ext.keyStoreDir = "$buildDir/keystore"
    ext.nativeBuildDir = "$projectDir/native/build"
    ext.enclaveBuildDir = "$projectDir/../enclave/build"

    ext.hardware = project.hasProperty("hardware") && (ext.hardware == "1" || ext.hardware == "yes" || ext.hardware == "true")
    ext.debug = project.hasProperty("debug") && (ext.debug == "1" || ext.debug == "yes" || ext.debug == "true")

    if (!project.hasProperty("debugPort")) {
        ext.debugPort = 5005
    } else {
        ext.debugPort = Integer.parseInt(ext.debugPort.toString())
    }

    if (ext.debug) {
        ext.debugArgs = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,timeout=10000,address=$debugPort"
    } else {
        ext.debugArgs = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$debugPort"
    }
}

apply from: 'utilities.gradle'
apply plugin: 'kotlin'
apply plugin: 'war'
apply plugin: 'org.akhikhl.gretty'

description 'Proof-of-Concept Remote Attestation Host'

import org.akhikhl.gretty.AppStartTask
import org.akhikhl.gretty.AppStopTask

configurations {
    integrationTestCompile.extendsFrom testCompile
    integrationTestRuntime.extendsFrom testRuntime
}

sourceSets {
    integrationTest {
        kotlin {
            compileClasspath += main.compileClasspath + test.compileClasspath
            runtimeClasspath += main.runtimeClasspath + test.runtimeClasspath
            //noinspection GroovyAssignabilityCheck
            srcDir file('src/integration-test/kotlin')
        }
    }
}

dependencies {
    compile project(':attestation-common')
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
    testCompile "junit:junit:$junit_version"

    compile "org.bouncycastle:bcpkix-jdk15on:$bouncycastle_version"
    compile "org.jboss.resteasy:resteasy-jaxrs:$resteasy_version"
    compile "org.jboss.resteasy:resteasy-jackson2-provider:$resteasy_version"
    compile "org.jboss.resteasy:resteasy-servlet-initializer:$resteasy_version"
    compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
    compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
    compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
    compile "org.apache.httpcomponents:httpclient:$httpclient_version"
    compile "org.apache.logging.log4j:log4j-slf4j-impl:$log4j_version"
    compile "org.apache.logging.log4j:log4j-core:$log4j_version"
    runtime "org.apache.logging.log4j:log4j-web:$log4j_version"
    compile "org.slf4j:jcl-over-slf4j:$slf4j_version"

    testCompile project(path: ':attestation-common', configuration: 'testArtifacts')
}

task createMockKeyStores(type: Exec) {
    doFirst {
        mkdir keyStoreDir
    }

    inputs.dir "$projectDir/src/main/ssl/mockisv"
    outputs.files "$keyStoreDir/dummyIAS.pfx", "$keyStoreDir/dummyIAS-trust.pfx"
    workingDir keyStoreDir
    commandLine "$projectDir/src/main/ssl/mockisv/generate-keystores.sh"
}

processResources {
    dependsOn createMockKeyStores
    from keyStoreDir
}

tasks.withType(Test) {
    // Enable "unlimited" encryption.
    systemProperties["java.security.properties"] = "$projectDir/src/main/security.properties"

    // Location of JNI object.
    systemProperties["java.library.path"] = nativeBuildDir

    // Location of enclave object.
    systemProperties["corda.sgx.enclave.path"] = enclaveBuildDir

    // Allow us to connect to JVM within enclave
    jvmArgs debugArgs
}

task integrationTest(type: Test) {
    testClassesDirs = sourceSets.integrationTest.output.classesDirs
    classpath = sourceSets.integrationTest.runtimeClasspath
    systemProperties["test.httpPort"] = testHttpPort
}

gretty {
    httpPort = testHttpPort
    contextPath = "/"
    servletContainer = 'tomcat8'
    logDir = "$buildDir/logs"
    logFileName = "gretty-test"
    integrationTestTask = 'integrationTest'
    jvmArgs = [
        "-Dorg.jboss.logging.provider=slf4j",
        "-Djava.security.properties=$projectDir/src/main/security.properties",
        "-Dattestation.home=$buildDir/logs",
        "-Disv.host=localhost:$testHttpPort/mockisv",
        "-Djava.library.path=$nativeBuildDir",
        "-Dcorda.sgx.enclave.path=$enclaveBuildDir",
    ]
}

task('startHost', type: AppStartTask, dependsOn: war) {
    prepareServerConfig {
        httpPort = hostHttpPort
        servletContainer = 'tomcat8'
        logDir = "$buildDir/logs"
        logFileName = "gretty-host"
        jvmArgs = [
            "-Dorg.jboss.logging.provider=slf4j",
            "-Djava.security.properties=$projectDir/src/main/security.properties",
            "-Dattestation.home=$buildDir/logs",
            "-Disv.host=localhost:$isvHttpPort",
            "-Djava.library.path=$nativeBuildDir",
            "-Dcorda.sgx.enclave.path=$enclaveBuildDir",
        ]
    }

    prepareWebAppConfig {
        contextPath = "/"
        inplace = false
    }

    interactive = false
}

task("stopHost", type: AppStopTask)

task cleanEnclave(type: Exec) {
    commandLine containerArgs("enclave", "clean")
}

task cleanJniLibrary(type: Exec) {
    commandLine containerArgs("attestation-host/native", "clean")
}

clean.dependsOn.addAll cleanEnclave, cleanJniLibrary

task buildEnclave(type: Exec) {
    commandLine containerArgs("enclave", "all")
}

task buildJniLibrary(type: Exec, dependsOn: [buildEnclave, classes]) {
    commandLine containerArgs("attestation-host/native", "all")
}

build.dependsOn.addAll buildJniLibrary

task runUnitTestsInContainer(type: Task, dependsOn: buildJniLibrary) {
    doLast { containerDebugWait(projectDir, "attestation-host", "unit-tests") }
}

task runIntegrationTestsInContainer(type: Task, dependsOn: buildJniLibrary) {
    doLast { containerDebugWait(projectDir, "attestation-host", "integration-tests") }
}

task debugUnitTestsInContainer(type: Task, dependsOn: buildJniLibrary) {
    doLast { containerDebugWait(projectDir, "attestation-host", "DEBUG=1", "unit-tests") }
}

task debugIntegrationTestsInContainer(type: Task, dependsOn: buildJniLibrary) {
    doLast { containerDebugWait(projectDir, "attestation-host", "DEBUG=1", "integration-tests") }
}