resource "kubernetes_service_account" "service_account" {
  metadata {
    name      = "${var.app_name}-backup-sa"
    namespace = var.namespace
  }

  automount_service_account_token = false
}

resource "kubernetes_secret" "scaleway_api_credentials" {
  metadata {
    name      = "${var.app_name}-scaleway-api-credentials"
    namespace = var.namespace
  }
  data = {
    access_key = var.access_key
    secret_key = var.secret_key
  }
  type = "Opaque"
}

resource "kubernetes_config_map" "rclone_config" {
  metadata {
    name      = "rclone-config"
    namespace = var.namespace
  }
  data = {
    "rclone.conf" = file("${path.module}/resources/rclone.conf")
  }
}

resource "kubernetes_cron_job_v1" "backup_job" {
  metadata {
    name      = "${var.app_name}-backup"
    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 = "${var.app_name}-backup"
        }
      }
      spec {
        backoff_limit           = 1
        parallelism             = 1
        completions             = 1
        active_deadline_seconds = 1800
        template {
          metadata {
            labels = {
              app = "${var.app_name}-backup"
            }
          }
          spec {
            service_account_name = kubernetes_service_account.service_account.metadata[0].name
            security_context {
              run_as_user = 0
            }
            container {

              name              = "${var.app_name}-backup"
              image             = "rclone/rclone:${local.rclone_version}"
              image_pull_policy = "Always"

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

              env {
                name = "SCW_ACCESS_KEY"
                value_from {
                  secret_key_ref {
                    key  = "access_key"
                    name = kubernetes_secret.scaleway_api_credentials.metadata[0].name
                  }
                }
              }
              env {
                name = "SCW_SECRET_KEY"
                value_from {
                  secret_key_ref {
                    key  = "secret_key"
                    name = kubernetes_secret.scaleway_api_credentials.metadata[0].name
                  }
                }
              }
              env {
                name  = "SCW_DEFAULT_PROJECT_ID"
                value = var.scaleway_project_id
              }
              env {
                name  = "SCW_DEFAULT_ORGANIZATION_ID"
                value = var.scaleway_organization_id
              }
              env {
                name  = "SCW_DEFAULT_REGION"
                value = var.scaleway_region
              }
              env {
                name  = "SCW_DEFAULT_ZONE"
                value = var.scaleway_zone
              }
              env {
                name  = "BUCKET_NAME"
                value = var.bucket_name
              }
              command = ["/bin/sh", "-c"]
              args = [join(";", [
                "apk update",
                "apk add gettext",
                "envsubst</etc/rclone.conf.tmpl>/etc/rclone.conf",
                "tar -zcvpf /backup/${var.app_name}-files-`date +\"%Y%m%d\"`.tar.gz /files",
                "find /backup -type f -name '${var.app_name}-files-*.tar.gz' -mtime +${var.retention_days} | xargs --no-run-if-empty rm",
                "/usr/local/bin/rclone --config=/etc/rclone.conf sync --progress /backup scaleway:$BUCKET_NAME/${var.app_name}-backup"
              ])]
              security_context {
                allow_privilege_escalation = false
              }
              volume_mount {
                name       = "backup-storage"
                mount_path = "/backup"
              }
              volume_mount {
                name       = "persistent-storage"
                mount_path = "/files"
                read_only  = true
              }
              volume_mount {
                name       = "rclone-conf"
                mount_path = "/etc/rclone.conf.tmpl"
                sub_path   = "rclone.conf"
                read_only  = true
              }
            }
            volume {
              name = "backup-storage"
              host_path {
                path = var.target_folder
              }
            }
            volume {
              name = "persistent-storage"
              host_path {
                path = var.source_folder
              }
            }
            volume {
              name = "rclone-conf"
              config_map {
                name = kubernetes_config_map.rclone_config.metadata[0].name
              }
            }
            restart_policy                   = "Never"
            termination_grace_period_seconds = 30
          }
        }
      }
    }
  }
}
