- hosts: containers
  name: Switch mailu to second
  
  ignore_unreachable: false
  vars:
      arch_name: docker_mailu2_data
      containers: 
        - nginx-app-1
        - heimdall
        - mailu2-admin-1
        - mailu2-antispam-1
        - mailu2-antivirus-1
        - mailu2-fetchmail-1
        - mailu2-front-1
        - mailu2-imap-1
        - mailu2-oletools-1
        - mailu2-redis-1
        - mailu2-resolver-1
        - mailu2-smtp-1
        - mailu2-webdav-1
        - mailu2-webmail-1
        - HomeAssistant
        - mosquitto-mosquitto-1
  tasks:
    - name: Start mailu containers
      command: "docker start {{ containers | join(' ') }}"
      become: true
      ignore_errors: true
      when: inventory_hostname in groups['raspberrypi5']

    - name: Get ruleset
      command: nvram get vts_rulelist
      when: inventory_hostname in groups['router']
      register: ruleset

    - name: Print the gateway for each host when defined
      ansible.builtin.debug:
        msg: "var is {{ ruleset.stdout }}"
      when: inventory_hostname in groups['router']


    - name: Print the gateway for each host when defined
      ansible.builtin.debug:
        msg: "var is {{ destination }}"
      when: inventory_hostname in groups['router']

    - name: initialize variables
      set_fact:                
        regexp: "\\g<1>{{ destination }}\\3"
      when: inventory_hostname in groups['router']

    - set_fact:
        app_path: "{{ ruleset.stdout | regex_replace('(\\<MAIL_SERVER\\>[0-9,]{1,}\\>)([0-9.]{1,})(\\>[0-9a-zA-Z\\s-]{0,}\\>TCP\\>)', regexp) | regex_replace('(\\<WEB_SERVER\\>[0-9,]{1,}\\>)([0-9.]{1,})(\\>[0-9a-zA-Z\\s-]{0,}\\>TCP\\>)', regexp) }}"
      when: inventory_hostname in groups['router']


    - name: Print the gateway for each host when defined
      ansible.builtin.debug:
        msg: "var is {{ app_path }}"
      when: inventory_hostname in groups['router']


    - name: Pause for 60 seconds
      ansible.builtin.pause:
        seconds: 60
        
    - name: Set new ruleset
      command: nvram set vts_rulelist="{{ app_path }}"
      when: inventory_hostname in groups['router']

    - name: Nvram commit
      command: nvram commit
      when: inventory_hostname in groups['router']

    - name: Restart firewall
      command: service restart_firewall
      when: inventory_hostname in groups['router']




      