---
# This role should be called before setting up the nodes
- name: define conditional variables
  set_fact:
    do_gateway_is_configured: false
    nat_gateway_is_configured: false
    do_wan_route_is_removed: false

- debug: var=nat_gateway_private_ip_eth1

- name: obtain DO gateway ip
  command: curl -s http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/gateway
  register: do_gateway_ip

- name: execute ip route show command
  command: ip route show
  register: do_gateway_route

- name: set do_gateway_is_configured to true if DO gateway is configured
  set_fact:
    do_gateway_is_configured: true
  when: do_gateway_route.stdout.find('169.254.168.254') != -1 and do_gateway_route.stdout.find(do_gateway_ip.stdout) != -1

- name: add route to DO gateway via eth0
  command: ip route add 169.254.168.254 via {{ do_gateway_ip.stdout }} dev eth0
  when: not do_gateway_is_configured

- name: execute ip route show command
  command: ip route show
  register: ip_route_output

- name: set nat_gateway_is_configured to true if nat gateway is configured
  set_fact:
    nat_gateway_is_configured: true
  when: ip_route_output.stdout.find(nat_gateway_private_ip_eth1) != -1

- name: change default route to private ip of DO droplet used as a safenode gateway
  command: ip route change default via {{ nat_gateway_private_ip_eth1 }}
  when: not nat_gateway_is_configured

- name: identify /20 CIDR network route from the routing table
  shell: ip route show | grep "dev eth0 proto kernel" | grep -v "\/16" | head -n 1 | awk '{print $1}'
  register: do_wanroute

- name: set do_wan_route_is_removed to true if /20 CIDR network route is removed
  set_fact:
    do_wan_route_is_removed: true
  when: do_wanroute.stdout == ""

- name: remove /20 CIDR network route from the routing table
  command: ip route del {{ do_wanroute.stdout }} dev eth0
  when: not do_wan_route_is_removed