resource "kubernetes_secret" "root_password" {
  metadata {
    name      = "${var.app_name}-root-credentials"
    namespace = var.namespace
  }
  data = {
    username = "root"
    password = var.root_password
  }
  type = "Opaque"
}

resource "kubernetes_service_account" "service_account" {

  metadata {
    name      = "${var.app_name}-mariadb-sa"
    namespace = var.namespace
  }

  automount_service_account_token = false
}

resource "kubernetes_secret" "app_password" {
  metadata {
    name      = "${var.app_name}-app-credentials"
    namespace = var.namespace
  }
  data = {
    username = var.app_name
    password = var.app_password
  }
  type = "Opaque"
}

resource "kubernetes_service" "service" {
  metadata {
    name      = "mariadb"
    namespace = var.namespace
  }
  spec {
    port {
      port = 3306
    }
    selector = {
      app = "mariadb"
    }
    cluster_ip = "None"
  }
}

resource "kubernetes_deployment" "deployment" {
  metadata {
    name      = "mariadb"
    namespace = var.namespace
  }
  spec {
    selector {
      match_labels = {
        app = "mariadb"
      }
    }
    strategy {
      type = "Recreate"
    }
    template {
      metadata {
        labels = {
          app = "mariadb"
        }
      }
      spec {
        service_account_name = kubernetes_service_account.service_account.metadata[0].name
        container {
          name  = "mariadb"
          image = "mariadb:${var.current_version}"

          resources {
            requests = {
              memory = "100Mi"
            }
          }

          liveness_probe {
            exec {
              command = ["sh", "-c", "mysqladmin status -uroot -p$MARIADB_ROOT_PASSWORD"]
            }
            initial_delay_seconds = 30
            period_seconds        = 300
            timeout_seconds       = 1
            failure_threshold     = 15
          }

          readiness_probe {
            exec {
              command = ["sh", "-c", "mysqladmin status -uroot -p$MARIADB_ROOT_PASSWORD"]
            }
            initial_delay_seconds = 120
            period_seconds        = 10
            timeout_seconds       = 1
            failure_threshold     = 15
          }

          env {
            name = "MARIADB_ROOT_PASSWORD"
            value_from {
              secret_key_ref {
                key  = "password"
                name = kubernetes_secret.root_password.metadata[0].name
              }
            }
          }
          env {
            name  = "MARIADB_ROOT_HOST"
            value = "10.%"
          }
          env {
            name = "MARIADB_USER"
            value_from {
              secret_key_ref {
                key  = "username"
                name = kubernetes_secret.app_password.metadata[0].name
              }
            }
          }
          env {
            name = "MARIADB_PASSWORD"
            value_from {
              secret_key_ref {
                key  = "password"
                name = kubernetes_secret.app_password.metadata[0].name
              }
            }
          }
          env {
            name  = "MARIADB_DATABASE"
            value = var.app_name
          }
          port {
            container_port = 3306
            name           = "mariadb"
          }
          volume_mount {
            mount_path = "/var/lib/mysql"
            name       = "persistent-storage"
          }
          volume_mount {
            mount_path = "/docker-entrypoint-initdb.d"
            name       = "initdb-storage"
          }
        }
        volume {
          name = "persistent-storage"
          host_path {
            path = "${var.database_folder}/${var.app_name}.data"
          }
        }
        volume {
          name = "initdb-storage"
          host_path {
            path = "${var.database_folder}/${var.app_name}.initdb.d"
          }
        }
      }
    }
  }
}

# TODO: This should move out of here
resource "kubernetes_cron_job_v1" "backup_data_cron" {
  metadata {
    name      = "mariadb-backup-job"
    namespace = var.namespace
  }
  spec {
    concurrency_policy            = "Forbid"
    schedule                      = var.cron_schedule
    failed_jobs_history_limit     = 2
    successful_jobs_history_limit = 2
    job_template {
      metadata {
        labels = {
          app = "mariadb"
        }
      }
      spec {
        backoff_limit           = 1
        parallelism             = 1
        completions             = 1
        active_deadline_seconds = 1800
        template {
          metadata {}
          spec {
            container {
              name  = "sql-cron-job"
              image = "mariadb:${var.current_version}"
              env {
                name = "MARIADB_USER"
                value_from {
                  secret_key_ref {
                    key  = "username"
                    name = kubernetes_secret.app_password.metadata[0].name
                  }
                }
              }
              env {
                name = "MARIADB_PASSWORD"
                value_from {
                  secret_key_ref {
                    key  = "password"
                    name = kubernetes_secret.app_password.metadata[0].name
                  }
                }
              }
              env {
                name  = "MARIADB_DATABASE"
                value = var.app_name
              }
              security_context {
                allow_privilege_escalation = false
              }
              command = ["/bin/sh", "-c"]
              args = [join(";", [
                "/usr/bin/mariadb-dump --single-transaction -h mariadb -u $MARIADB_USER -p$MARIADB_PASSWORD $MARIADB_DATABASE | gzip > /backups/${var.app_name}-sql-`date +\"%Y%m%d\"`.sql.gz",
                "find /backups -type f -name '${var.app_name}-sql-*.sql.gz' -mtime +${var.retention_days} | xargs --no-run-if-empty rm"
              ])]
              volume_mount {
                mount_path = "/backups"
                name       = "backups-storage"
              }
            }
            volume {
              name = "backups-storage"
              host_path {
                path = var.backup_folder
              }
            }
            restart_policy                   = "Never"
            termination_grace_period_seconds = 30
          }
        }
      }
    }
  }
}
