configurations {
    api {
        transitive = false
    }
}

dependencies {
    api project(path: ":api:controller", configuration: "controller")
}

task copyApi(type: Copy) {
    dependsOn(':api:controller:build')
    from configurations.api
    into "api" 
}

def inputFiles = [
    project.file("cloudbuild.yaml"),
    project.file("Dockerfile")
]

def getDateSuffix() {
    return "-" + new Date().format('yyyyMMddHHmmss')
}

def env = System.getenv()
def gcpProjectID = env["BPG_GCP_PROJECT_ID"]
def imageTag = 'gcr.io/' + gcpProjectID +'/playground-controller:' + project.version + getDateSuffix()


task clean(type: Delete) {
   delete 'api', 'plugins'
   followSymlinks = true
}

task cloudBuild(type: Exec) {
    dependsOn clean
    dependsOn copyApi
    inputs.files(inputFiles)
    commandLine "gcloud", "builds", "submit", "--config", "cloudbuild.yaml", 
        '--substitutions=_IMAGE_TAG=' + imageTag, "."
}

task build(type: Exec) {
    dependsOn clean
    dependsOn copyApi
    inputs.files(inputFiles)
    commandLine 'docker', 'build', '-t', imageTag, '.'
}

def containerIdFile = new File(projectDir, "containerId.txt");
if (!containerIdFile.exists()) {
    containerIdFile.write("");
}

task start(type: Exec) {
    dependsOn build
    commandLine "docker", "run", 
        "--env", "COMPILER_HOST=ws://docker.for.mac.host.internal:9091/compiler", 
        "--env", "EXECUTOR_HOST=ws://docker.for.mac.host.internal:9092/executor",
        "--env", "REDIS_WRITE_HOST=docker.for.mac.host.internal",
        "--env", "REDIS_READ_HOST=docker.for.mac.host.internal",
        "-d", "-p", "9090:9090", imageTag
    standardOutput = new ByteArrayOutputStream()
	doLast {
        containerIdFile.text = standardOutput.toString()
        println standardOutput.toString()
	}
}

task logs(type: Exec) {
    commandLine "docker", "logs", "-f", containerIdFile.text.trim()
}

task stop(type: Exec) {
    commandLine "docker", "kill", containerIdFile.text.trim()
    doLast {
        containerIdFile.text = ""
	}
}
