resource "kubernetes_namespace" "trivy" {
  metadata {
    name = "trivy"
  }
}

resource "kubernetes_service_account" "trivy" {
  metadata {
    name      = "trivy"
    namespace = kubernetes_namespace.trivy.metadata[0].name
  }

  automount_service_account_token = false
}

resource "kubernetes_cluster_role" "trivy" {
  metadata {
    name = "trivy"
  }
  rule {
    api_groups = [""]
    resources  = ["*"]
    verbs      = ["list"]
  }
  rule {
    api_groups = ["apps", "batch", "networking.k8s.io", "rbac.authorization.k8s.io"]
    resources  = ["*"]
    verbs      = ["list"]
  }
}

resource "kubernetes_cluster_role_binding" "trivy" {
  metadata {
    name = "trivy"
  }
  role_ref {
    api_group = "rbac.authorization.k8s.io"
    kind      = "ClusterRole"
    name      = kubernetes_cluster_role.trivy.metadata[0].name
  }
  subject {
    kind      = "ServiceAccount"
    name      = kubernetes_service_account.trivy.metadata[0].name
    namespace = kubernetes_namespace.trivy.metadata[0].name
  }
}

resource "kubernetes_secret" "email_credentials" {
  metadata {
    name      = "trivy-email-credentials"
    namespace = kubernetes_namespace.trivy.metadata[0].name
  }
  data = {
    smtp_username = var.smtp_username
    smtp_password = var.smtp_password
  }
}

resource "kubernetes_config_map" "send_report" {
  metadata {
    name      = "trivy-send-report"
    namespace = kubernetes_namespace.trivy.metadata[0].name
  }
  data = {
    "send_report.py" = local.send_report_script
  }
}

resource "kubernetes_cron_job_v1" "trivy" {
  metadata {
    name      = "trivy-scan"
    namespace = kubernetes_namespace.trivy.metadata[0].name
  }
  spec {
    schedule                      = var.cron_schedule
    concurrency_policy            = "Forbid"
    successful_jobs_history_limit = 1
    failed_jobs_history_limit     = 1
    job_template {
      metadata {
        name = "trivy-scan"
      }
      spec {
        backoff_limit           = 1
        parallelism             = 1
        completions             = 1
        active_deadline_seconds = 250

        template {
          metadata {
            labels = {
              app = "trivy-scan"
            }
          }
          spec {
            restart_policy                  = "Never"
            service_account_name            = kubernetes_service_account.trivy.metadata[0].name
            automount_service_account_token = true
            container {
              image = "aquasec/trivy:${var.tag}"
              name  = "trivy"
              args  = ["k8s", "--report=${var.report_type}", "--exit-code=0", "--severity=${var.levels}", "--cache-dir=/cache", "-o", "/reports/trivy.txt", "--disable-node-collector"]
              volume_mount {
                name       = "trivy-reports"
                mount_path = "/reports"
              }
              volume_mount {
                name       = "trivy-cache"
                mount_path = "/cache"
              }
            }
            container {
              name  = "send-report"
              image = "python:${local.python_version}"
              args  = ["/scripts/send_report.py"]
              env {
                name  = "REPORT_PATH"
                value = "/reports/trivy.txt"
              }
              env {
                name  = "SMTP_HOST"
                value = var.smtp_host
              }
              env {
                name  = "SMTP_PORT"
                value = var.smtp_port
              }
              env {
                name = "SMTP_USER"
                value_from {
                  secret_key_ref {
                    key  = "smtp_username"
                    name = kubernetes_secret.email_credentials.metadata[0].name
                  }
                }
              }
              env {
                name = "SMTP_PASS"
                value_from {
                  secret_key_ref {
                    key  = "smtp_password"
                    name = kubernetes_secret.email_credentials.metadata[0].name
                  }
                }
              }
              env {
                name  = "EMAIL_FROM"
                value = var.from_email
              }
              env {
                name  = "EMAIL_TO"
                value = var.to_email
              }
              volume_mount {
                name       = "trivy-reports"
                mount_path = "/reports"
              }
              volume_mount {
                name       = "trivy-scripts"
                mount_path = "/scripts"
              }
            }
            volume {
              name = "trivy-reports"
              empty_dir {}
            }
            volume {
              name = "trivy-cache"
              host_path {
                path = local.cache_path
              }
            }
            volume {
              name = "trivy-scripts"
              config_map {
                name         = kubernetes_config_map.send_report.metadata[0].name
                default_mode = "0755"

              }
            }
          }
        }
      }
    }
  }
}
