resource "docker_network" "unifi" {
  name = "unifi"
}

data "docker_registry_image" "mongo" {
  name = local.docker_image_mongo
}

resource "docker_image" "mongo" {
  name          = data.docker_registry_image.mongo.name
  pull_triggers = [data.docker_registry_image.mongo.sha256_digest]
}

resource "docker_volume" "unifi-mongo" {
  name = "unifi-mongo"
}

resource "docker_container" "unifi-mongo" {
  image    = docker_image.mongo.image_id
  name     = "unifi-mongo"
  hostname = "unifi-mongo"

  networks_advanced {
    name = docker_network.unifi.name
  }

  volumes {
    volume_name    = docker_volume.unifi-mongo.name
    container_path = "/data/db"
  }
}

output "mongo_init_js" {
  sensitive = true
  value = <<-EOF
  db.getSiblingDB("${local.mongo_database}").
    createUser({
      user: "${local.mongo_database}",
      pwd: "${local.mongo_password}",
      roles: [{role: "dbOwner", db: "${local.mongo_database}"}]});

  db.getSiblingDB("${local.mongo_database}_stat").
    createUser({
      user: "${local.mongo_database}",
      pwd: "${local.mongo_password}",
      roles: [{role: "dbOwner", db: "${local.mongo_database}_stat"}]});
  EOF
}