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 = {
	    	as400_proxy_asadmin_Xms = var.as400_proxy_asadmin_Xms
	    	as400_proxy_asadmin_Xmx = var.as400_proxy_asadmin_Xmx
	    	as400_proxy_asadmin_httpThreadPoolMinThreadPoolSize = var.as400_proxy_asadmin_httpThreadPoolMinThreadPoolSize
			as400_proxy_asadmin_httpThreadPoolMaxThreadPoolSize = var.as400_proxy_asadmin_httpThreadPoolMaxThreadPoolSize
	    }
	}
}

resource "docker_image" "as400-proxy-image" {
  name = "${var.as400_proxy_image_name}-${var.as400_proxy_payara_version}"
  build {
    context = "./docker"
    build_args = {
    	as400_proxy_payara_version = var.as400_proxy_payara_version
    }
  }
  depends_on = [null_resource.createBootFile]
}

resource "docker_container" "as400-proxy-container" {
  image   = "${var.as400_proxy_image_name}-${var.as400_proxy_payara_version}"
  restart = "unless-stopped"
  init = true
  name    = var.as400_proxy_container_name
  network_mode = var.as400_proxy_network_mode
  entrypoint = ["/usr/lib/jvm/zulu8-ca/bin/java","-jar","/opt/payara/payara-micro.jar","--nocluster","--deploymentDir","/opt/payara/deployments","--postbootcommandfile","/opt/payara/as400proxyPostBootFile.txt"] 

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

  volumes {
    container_path = "/opt/payara/etc/as400-proxy"
    host_path      = var.as400_proxy_etc_volume
  }

  volumes {
    container_path = "/opt/payara/var/as400-proxy"
    host_path      = var.as400_proxy_var_volume
  }

  volumes {
    container_path = "/opt/payara/deployments"
    host_path      = var.as400_proxy_deployments_volume
  }
  
  env = ["SERVER=${var.as400_proxy_server}", "USER=${var.as400_proxy_user}", "PASSWORD=${var.as400_proxy_password}", "TOKEN_DURATION=${var.as400_proxy_token_duration}", "SECRET=${var.as400_proxy_secret}", "SSL_CONNECTION=${var.as400_proxy_ssl_connection}", "SSL_SELF_SIGNED_ALLOWED=${var.as400_proxy_ssl_self_signed_allowed}", "SSL_CERTS_FOLDER_PATH=${var.ssl_certs_folder_path}", "SSL_TRUSTSTORE_FILEPATH=${var.ssl_trustore_filepath}"]
  
  depends_on = [null_resource.createBootFile, docker_image.as400-proxy-image]
}

#resource "docker_image" "payara-micro" {
#  name = "payara/micro:5.182"
#  keep_locally = "true"
#}

