#!/bin/bash
#
set -e
#
# Create bash profile script
#
cat <<SCRIPT >/root/.bash_profile
#!/bin/bash
#
export PS1="\h(bash)#"
echo "Use vtysh to connect to FRR daemon"
echo
SCRIPT
#
# Build hosts file
#
hostname {{ inventory_hostname }}
{% if ansible_connection != "docker" %}
awk '/127.0.1.1/,/^$/' /etc/hosts >/tmp/hosts
echo "127.0.0.1 {{ inventory_hostname }}" >>/tmp/hosts
{% for k,v in hostvars.items() if v.loopback.ipv4 is defined and k != inventory_hostname %}
echo "{{ v.loopback.ipv4|ipaddr('address') }}{%- for l in v.links|default([]) if l.ipv4 is defined %} {{ l.ipv4|ipaddr('address') }}{%- endfor %} {{ k }}" >>/tmp/hosts
{% endfor %}
cat /etc/hosts | awk '/localhost/,/^$/' >/tmp/hosts-start
mv /tmp/hosts-start /etc/hosts
sort /tmp/hosts|uniq >>/etc/hosts
{% endif %}
#
# Enable LLDP
#
cat <<CONFIG >/etc/lldpd.d/system.conf
configure lldp tx-interval 30
configure lldp tx-hold 3
configure system interface pattern *,!eth0,swp*
CONFIG
service lldpd restart
#
# Enable FRR modules
#
{% set modlist = {'bgp':'bgpd','ospf':'ospfd','isis':'isisd'} %}
{% for m in module|default([]) if modlist[m] is defined %}
echo "{{ modlist[m] }}=yes" >>/etc/frr/daemons
{% endfor %}
systemctl enable frr.service
systemctl start frr.service
systemctl reload frr.service
#
# Rest of initial configuration done through VTYSH
#
cat >/tmp/config <<CONFIG
ipv6 forwarding
!
interface lo
 no shutdown
{% if 'ipv4' in loopback %}
 ip address {{ loopback.ipv4 }}
{% endif %}
{% if 'ipv6' in loopback %}
 ipv6 address {{ loopback.ipv6 }}
{% endif %}
!
{% for l in links|default([]) %}
interface {{ l.ifname }}
! no shutdown
{% if l.name is defined %}
 description {{ l.name }}{{ " ["+l.role+"]" if l.role is defined else "" }}
{% elif l.type|default("") == "stub" %}
 description Stub interface
{% endif %}
{% if l.ipv4 is defined %}
 ip address {{ l.ipv4 }}
{% endif %}
{% if l.ipv6 is defined %}
 ipv6 address {{ l.ipv6 }}
{% endif %}
{% if l.bandwidth is defined %}
 bandwidth {{ l.bandwidth  }}
{% endif %}
!
{% endfor %}
do write
CONFIG
vtysh -f /tmp/config
