resource "kubernetes_service_account" "proxy" {

  metadata {
    name      = "wol-proxy-sa"
    namespace = kubernetes_namespace.proxy.metadata[0].name
  }

  automount_service_account_token = false
}

resource "kubernetes_deployment" "proxy" {

  metadata {
    name      = "wol-proxy"
    namespace = kubernetes_namespace.proxy.metadata[0].name
    labels = {
      app = "wol-proxy"
    }
  }

  spec {
    replicas = 1
    selector {
      match_labels = {
        app = "wol-proxy"
      }
    }

    strategy {
      type = "Recreate"
    }

    template {
      metadata {
        labels = {
          app = "wol-proxy"
        }
      }

      spec {
        service_account_name            = kubernetes_service_account.proxy.metadata[0].name
        automount_service_account_token = false

        host_network = true
        container {
          name              = "app"
          image             = "a13labs/wol_proxy:${var.tag}"
          image_pull_policy = "Always"

          security_context {
            capabilities {
              add = ["NET_RAW"]
            }
          }

          port {
            name           = "upstream"
            container_port = var.proxy_port
          }

          env {
            name  = "UPSTREAM_MAC"
            value = var.upstream.mac
          }

          env {
            name  = "UPSTREAM_IP"
            value = var.upstream.ip
          }

          env {
            name  = "UPSTREAM_PORT"
            value = var.upstream.port
          }

          env {
            name  = "UPSTREAM_SCHEME"
            value = var.upstream.scheme
          }

          env {
            name  = "PROXY_PORT"
            value = var.proxy_port
          }

          readiness_probe {
            tcp_socket {
              port = var.proxy_port
            }
            initial_delay_seconds = 5
            period_seconds        = 10
            failure_threshold     = 10
          }
        }
      }
    }
  }
}

resource "kubernetes_service" "proxy" {
  metadata {
    name      = "upstream"
    namespace = kubernetes_namespace.proxy.metadata[0].name
  }

  spec {
    selector = {
      app = "wol-proxy"
    }

    port {
      name        = "upstream"
      port        = var.proxy_port
      target_port = var.proxy_port
    }
  }

  lifecycle {
    ignore_changes = [
      metadata[0].annotations
    ]
  }
}
