terraform {
  required_providers {
    docker = {
      source = "kreuzwerker/docker"
      version = "3.0.1"
    }
  }
}

provider "docker" {
      host    = "unix:///var/run/docker.sock"
}

resource "null_resource" "createBootFile" {
	provisioner "local-exec" {
	    command = "/bin/bash ./docker/createPostBootFile.sh"
	    environment = {
	    	h53_asadmin_Xms = var.h53_asadmin_Xms
	    	h53_asadmin_Xmx = var.h53_asadmin_Xmx
	    	h53_asadmin_httpThreadPoolMinThreadPoolSize = var.h53_asadmin_httpThreadPoolMinThreadPoolSize
			h53_asadmin_httpThreadPoolMaxThreadPoolSize = var.h53_asadmin_httpThreadPoolMaxThreadPoolSize
	    }
	}
}
  
resource "docker_image" "h53-image" {
  name = "${var.h53_image_name}-${var.h53_payara_version}"
  build {
    context = "./docker"
    build_args = {
    	h53_payara_version = var.h53_payara_version
    }
  }
  depends_on = [null_resource.createBootFile]
}

resource "docker_container" "h53-container" {

  image   = "${var.h53_image_name}-${var.h53_payara_version}"
  restart = "unless-stopped"
  init = true
  name    = var.h53_container_name
  network_mode = var.h53_network_mode
  entrypoint = ["/usr/lib/jvm/zulu8-ca/bin/java","-jar","/opt/payara/payara-micro.jar","--nocluster","--deploymentDir","/opt/payara/deployments","--postbootcommandfile","/opt/payara/h53PostBootFile.txt"] 

  ports {
    internal = 8080
    ip = "127.0.0.1"
    external = var.h53_http_external_port
  }

  volumes {
    container_path = "/opt/payara/etc/h53"
    host_path      = var.h53_etc_volume
  }

  volumes {
    container_path = "/opt/payara/var/h53"
    host_path      = var.h53_var_volume
  }

  volumes {
    container_path = "/opt/payara/deployments"
    host_path      = var.h53_deployments_volume
  }
  
  volumes {
    volume_name    = var.h53_share_0
    container_path = "/mnt/share_0"
  }
  
  depends_on = [null_resource.createBootFile, docker_image.h53-image, docker_volume.shared-volumes ]
 
}

resource "docker_volume" "shared-volumes" {
  count       = length(var.h53_shares)
  driver_opts = var.h53_shares[element(keys(var.h53_shares), count.index)]
  name        = element(keys(var.h53_shares), count.index)
}
