{% set config = merged_configs.get('azurerm_recovery_services_vault', {}) %}
{% set comments = compliance_comments.get('azurerm_recovery_services_vault', []) %}
# ------------------------------------------------------------------------------
# Azure Recovery Services Vault
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "azurerm_recovery_services_vault" "this" {
  name                = "{{ config.get('name', project_id ~ '-rsv') }}"
  resource_group_name = var.resource_group_name
  location            = var.region

  sku = "{{ config.get('sku', 'Standard') }}"

  soft_delete_enabled = {{ config.get('soft_delete_enabled', true) | lower }}

  {% if config.get('immutability') %}
  immutability = "{{ config.immutability }}"
  {% endif %}

  {% if config.get('cross_region_restore_enabled', false) %}
  cross_region_restore_enabled = true
  {% endif %}

  {% if config.get('storage_mode_type') %}
  storage_mode_type = "{{ config.storage_mode_type }}"
  {% endif %}

  {% if config.get('encryption') %}
  encryption {
    key_id                            = "{{ config.encryption.key_id }}"
    infrastructure_encryption_enabled = {{ config.encryption.get('infrastructure_encryption_enabled', true) | lower }}
    use_system_assigned_identity      = {{ config.encryption.get('use_system_assigned_identity', true) | lower }}
  }
  {% endif %}

  identity {
    type = "{{ config.get('identity_type', 'SystemAssigned') }}"
  }

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

resource "azurerm_backup_policy_vm" "this" {
  name                = "{{ config.get('policy_name', project_id ~ '-vm-backup-policy') }}"
  resource_group_name = var.resource_group_name
  recovery_vault_name = azurerm_recovery_services_vault.this.name

  backup {
    frequency = "{{ config.get('backup_frequency', 'Daily') }}"
    time      = "{{ config.get('backup_time', '23:00') }}"
  }

  retention_daily {
    count = {{ config.get('daily_retention_count', 30) }}
  }

  {% if config.get('weekly_retention_count') %}
  retention_weekly {
    count    = {{ config.weekly_retention_count }}
    weekdays = {{ config.get('weekly_retention_weekdays', '["Sunday"]') }}
  }
  {% endif %}

  {% if config.get('monthly_retention_count') %}
  retention_monthly {
    count    = {{ config.monthly_retention_count }}
    weekdays = {{ config.get('monthly_retention_weekdays', '["Sunday"]') }}
    weeks    = {{ config.get('monthly_retention_weeks', '["Last"]') }}
  }
  {% endif %}
}
