# ---------- Database: a SQL Server container outside the cluster, one per environment ----------

resource "random_password" "sa" {
  length           = 20
  min_upper        = 2
  min_lower        = 2
  min_numeric      = 2
  min_special      = 1
  special          = true
  override_special = "!#-_"
}

resource "docker_volume" "sqldata" {
  name = "${var.environment}-sqldata"
}

resource "docker_image" "sql" {
  name         = "mcr.microsoft.com/mssql/server:2022-latest"
  platform     = "linux/amd64"
  keep_locally = true
}

resource "docker_container" "db" {
  name  = "${var.environment}-db"
  image = docker_image.sql.image_id

  env = [
    "ACCEPT_EULA=Y",
    "MSSQL_SA_PASSWORD=${random_password.sa.result}",
  ]

  # The "kind" network belongs to the cluster, so the pods can reach the database by name.
  networks_advanced {
    name = "kind"
  }

  volumes {
    volume_name    = docker_volume.sqldata.name
    container_path = "/var/opt/mssql"
  }

  healthcheck {
    test         = ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P \"$MSSQL_SA_PASSWORD\" -Q 'SELECT 1' || exit 1"]
    interval     = "5s"
    timeout      = "3s"
    retries      = 20
    start_period = "5s"
  }

  wait         = true
  wait_timeout = 120
}

resource "terraform_data" "db_schema" {
  triggers_replace = [
    filesha1("${path.module}/db/init.sql"),
    docker_container.db.id,
  ]

  provisioner "local-exec" {
    command = "docker cp ${path.module}/db/init.sql ${docker_container.db.name}:/tmp/init.sql && docker exec -e SQLCMDPASSWORD=\"$SA_PASSWORD\" ${docker_container.db.name} /opt/mssql-tools18/bin/sqlcmd -C -b -S localhost -U sa -i /tmp/init.sql"

    environment = {
      SA_PASSWORD = random_password.sa.result
    }
  }
}

# ---------- The web image, built and loaded into the cluster ----------

locals {
  source_hash = sha1(join("", [
    for f in sort(fileset("${path.module}/app", "*")) :
    filesha1("${path.module}/app/${f}")
  ]))
  site_image = "terraform-demo-site:${substr(local.source_hash, 0, 8)}"
}

resource "docker_image" "site" {
  name         = local.site_image
  keep_locally = true

  build {
    context = "${path.module}/app"
  }
}

resource "terraform_data" "load_image" {
  triggers_replace = [docker_image.site.image_id]

  provisioner "local-exec" {
    command = "docker save ${local.site_image} | docker exec -i ${var.cluster_node} ctr --namespace=k8s.io images import --all-platforms -"
  }
}

# ---------- The Kubernetes objects, in a namespace named after the environment ----------

resource "kubernetes_namespace_v1" "env" {
  metadata {
    name = var.environment
  }
}

resource "kubernetes_secret_v1" "db" {
  metadata {
    name      = "db-connection"
    namespace = kubernetes_namespace_v1.env.metadata[0].name
  }

  data = {
    DB_CONNECTION = "Server=${docker_container.db.name};Database=ShopDemo;User Id=sa;Password=${random_password.sa.result};TrustServerCertificate=True"
  }
}

resource "kubernetes_deployment_v1" "site" {
  metadata {
    name      = "site"
    namespace = kubernetes_namespace_v1.env.metadata[0].name
  }

  spec {
    replicas = var.instances

    selector {
      match_labels = {
        app = "site"
      }
    }

    strategy {
      type = "RollingUpdate"

      rolling_update {
        max_surge       = "1"
        max_unavailable = "0"
      }
    }

    template {
      metadata {
        labels = {
          app = "site"
        }
      }

      spec {
        container {
          name              = "site"
          image             = local.site_image
          image_pull_policy = "IfNotPresent"

          port {
            container_port = 8080
          }

          env {
            name  = "ENVIRONMENT"
            value = var.environment
          }

          env {
            name  = "SITE_TITLE"
            value = var.site_title
          }

          env {
            name  = "SITE_COLOR"
            value = var.site_color
          }

          env {
            name = "DB_CONNECTION"

            value_from {
              secret_key_ref {
                name = kubernetes_secret_v1.db.metadata[0].name
                key  = "DB_CONNECTION"
              }
            }
          }

          readiness_probe {
            http_get {
              path = "/healthz"
              port = 8080
            }

            period_seconds    = 2
            failure_threshold = 2
          }

          liveness_probe {
            http_get {
              path = "/healthz"
              port = 8080
            }

            initial_delay_seconds = 5
            period_seconds        = 5
            failure_threshold     = 3
          }
        }
      }
    }
  }

  depends_on = [terraform_data.load_image, terraform_data.db_schema]
}

resource "kubernetes_service_v1" "site" {
  metadata {
    name      = "site"
    namespace = kubernetes_namespace_v1.env.metadata[0].name
  }

  spec {
    type = "NodePort"

    selector = {
      app = "site"
    }

    port {
      port        = 80
      target_port = 8080
      node_port   = var.node_port
    }
  }
}
