variable "wait_on" {
  type        = any
  description = "Resources to wait on"
  default     = true
}

variable "server_ip" {
  type = string
}

variable "ssh_private_key_path" {
  type = string
}

variable "server_domain" {
  type = string
}

variable "server_url" {
  type    = string
  default = "https://mail.binarysunset.dev"
}

# tmail-web reads its configuration from a file at
# /usr/share/nginx/html/assets/env.file inside the container. Setting
# SERVER_URL as a container environment variable does NOT work (see
# https://github.com/linagora/tmail-flutter/issues/4240); the file must
# be injected. We write it to the host and bind-mount it into the
# container.
locals {
  env_file_host_path      = "/opt/storage/data/tmail-web/env.file"
  env_file_container_path = "/usr/share/nginx/html/assets/env.file"
  env_file_content        = "SERVER_URL=${var.server_url}\nDOMAIN_REDIRECT_URL=mail.${var.server_domain}\n"
}

resource "null_resource" "tmail_env_file" {
  triggers = {
    content   = local.env_file_content
    server_ip = var.server_ip
    host_path = local.env_file_host_path
  }

  provisioner "remote-exec" {
    inline = [
      "mkdir -p $(dirname ${local.env_file_host_path})",
      "cat > ${local.env_file_host_path} << 'EOF'",
      local.env_file_content,
      "EOF",
    ]

    connection {
      type           = "ssh"
      host           = var.server_ip
      user           = "fourlights"
      agent          = true
      agent_identity = var.ssh_private_key_path
    }
  }
}

module "tmail-web" {
  source  = "../quadlet-app"
  wait_on = var.wait_on

  server_ip            = var.server_ip
  ssh_private_key_path = var.ssh_private_key_path

  app_name = "tmail-web"
  image    = "docker.io/linagora/tmail-web:latest"
  ports    = ["8080:80"]
  volumes  = ["${local.env_file_host_path}:${local.env_file_container_path}:ro"]

  environment = {}

  haproxy_services = [
    {
      name   = "tmail-web"
      domain = "mail.${var.server_domain}"
      port   = "8080"
      host   = "127.0.0.1"
      tls    = false
    }
  ]

  healthcmd = "curl -f http://localhost:80 || exit 1"

  depends_on = [null_resource.tmail_env_file]
}

output "app_urls" {
  value = module.tmail-web.app_urls
}

output "installed" {
  value      = true
  depends_on = [module.tmail-web.installed]
}
