locals {
  config_data = file("${path.module}/config.yml")
}

resource "nomad_job" "blocky" {
  hcl2 {
    vars = {
      "config_data" = local.config_data,
    }
  }

  jobspec = templatefile("${path.module}/blocky.nomad", {
    use_wesher = var.use_wesher,
  })
}

# Generate secrets and policies for access to MySQL
resource "nomad_acl_policy" "blocky_mysql_bootstrap_secrets" {
  name        = "blocky-secrets-mysql"
  description = "Give access to MySQL secrets"
  rules_hcl   = <<EOH
namespace "default" {
  variables {
    path "secrets/mysql" {
      capabilities = ["read"]
    }
  }
}
EOH

  job_acl {
    job_id = "blocky"
    group  = "blocky"
    task   = "mysql-bootstrap"
  }
}

resource "random_password" "blocky_mysql_psk" {
  length           = 32
  override_special = "!@#%&*-_="
}

resource "nomad_variable" "blocky_mysql_psk" {
  path = "secrets/mysql/allowed_psks/blocky"
  items = {
    psk = "blocky:${resource.random_password.blocky_mysql_psk.result}"
  }
}

resource "nomad_acl_policy" "blocky_mysql_psk" {
  name        = "blocky-secrets-mysql-psk"
  description = "Give access to MySQL PSK secrets"
  rules_hcl   = <<EOH
namespace "default" {
  variables {
    path "secrets/mysql/allowed_psks/blocky" {
      capabilities = ["read"]
    }
  }
}
EOH

  job_acl {
    job_id = "blocky"
    group  = "blocky"
    task   = "stunnel"
  }
}