{% from "templates/initial/srlinux.j2" import ip_addresses with context %}

updates:
{% for l in interfaces|default([]) if l.vlan is defined %}
{% set if_name_index = l.ifname.split('.') %}
{% set if_name = if_name_index[0] if l.type!='stub' else "lo0" %}
{% set if_index = if_name_index[1] if if_name_index|length > 1 else l.ifindex if l.type=='stub' else l.vlan.access_id|default(0) -%}

{# 1. Create the interface, configure tagging for vlan_members or trunk ports with native vlans #}
- path: interface[name={{if_name}}]
  val:
{% if l.vlan.trunk_id is defined %}
{% set _desc = l.name|default("without a name") | replace('->','~')|regex_replace('[\\[\\]]','') %}
   description: "Trunk port {{ _desc }} native={{ l.vlan.native|default("not set") }}"
{% endif %}
{% if l.type=='vlan_member' or l.vlan.trunk_id is defined %}
   vlan-tagging: True
{% endif %}
{% if not (l.vlan.trunk_id is defined and l.vlan.native is not defined) %}{# Skip trunk ports without native vlan #}
   subinterface:
   - index: {{ if_index }}
{%  if l.type in ['vlan_member','lan'] or l.vlan.trunk_id is defined %}
{#   Untagged native vlan only allows type bridged, routing via irb interface #}
     type: {{ 'routed' if l.vlan.mode|default('irb') == 'route' else 'bridged' }}
{%   if l.name is defined %}
     description: "{{ l.name | replace('->','~')|regex_replace('[\\[\\]]','') }}"
{%   endif %}
{%   if l.type=='vlan_member' or l.vlan.trunk_id is defined %}
     vlan:
      encap:
{%     if l.vlan.native is defined %}
       untagged:
        _annotate: "Native VLAN {{ l.vlan.access_id }}"
{%     else %}
       single-tagged:
        vlan-id: "{{ l.vlan.access_id }}"
{%     endif %}
{%    endif %}
{%  endif %}

{%  if l.ipv4 is defined or l.ipv6 is defined %}
{{   ip_addresses(if_name,if_index,l) }}
{%  endif %}
{% endif %} {# interface definition #}

{# Create mac-vrf for L2 VLANs, add L2 side of IRB interface if any #}
{# Use only vlan.id in name, such that svi interfaces (irb0.nnnn) can be associated #}
{% set vlan_mode = l.vlan.mode|default('irb') %}
{% if (l.type in ['vlan_member','lan'] and vlan_mode!='route') or (l.type=='svi' and vlan_mode=='irb') %}
- path: network-instance[name=vlan{{ if_index }}]
  val:
   type: mac-vrf
{% if l.name is defined %}
   description: "{{ l.name | replace('->','~')|regex_replace('[\\[\\]]','') }}"
{% endif %}
   interface:
   - name: {{ if_name }}.{{ if_index }}
{% endif %}

{# Add L3 interfaces to IP VRF #}
{% if l.ipv4 is defined or l.ipv6 is defined %}
- path: network-instance[name={{ l.vrf|default('default') }}]
  val:
   type: {{ 'default' if l.vrf|default('default')=='default' else 'ip-vrf' }}
   interface:
   - name: {{ if_name }}.{{ if_index }}
{% endif %}

{% endfor %} {# for l in interfaces #}
