{% set config = merged_configs.get('aws_backup_vault', {}) %}
{% set comments = compliance_comments.get('aws_backup_vault', []) %}
# ------------------------------------------------------------------------------
# AWS Backup Vault and Plan
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "aws_backup_vault" "this" {
  name        = "{{ config.get('name', project_id ~ '-backup-vault') }}"
  kms_key_arn = {{ config.get('kms_key_arn', 'null') }}

  tags = {
    Name      = "{{ config.get('name', project_id ~ '-backup-vault') }}"
    ManagedBy = "complyform"
  }
}

resource "aws_backup_vault_lock_configuration" "this" {
  backup_vault_name   = aws_backup_vault.this.name
  min_retention_days  = {{ config.get('min_retention_days', 35) }}
  max_retention_days  = {{ config.get('max_retention_days', 365) }}
}

resource "aws_backup_plan" "this" {
  name = "{{ config.get('plan_name', project_id ~ '-backup-plan') }}"

  rule {
    rule_name         = "{{ config.get('rule_name', 'daily-backup') }}"
    target_vault_name = aws_backup_vault.this.name
    schedule          = "{{ config.get('schedule', 'cron(0 3 * * ? *)') }}"
    start_window      = {{ config.get('start_window', 60) }}
    completion_window = {{ config.get('completion_window', 180) }}

    lifecycle {
      delete_after = {{ config.get('delete_after_days', 35) }}

      {% if config.get('cold_storage_after_days') %}
      cold_storage_after = {{ config.cold_storage_after_days }}
      {% endif %}
    }

    {% if config.get('copy_to_vault_arn') %}
    copy_action {
      destination_vault_arn = "{{ config.copy_to_vault_arn }}"

      lifecycle {
        delete_after = {{ config.get('copy_delete_after_days', 365) }}
      }
    }
    {% endif %}
  }

  tags = {
    Name      = "{{ config.get('plan_name', project_id ~ '-backup-plan') }}"
    ManagedBy = "complyform"
  }
}
