---
- name: Acquiring home of current user
  when: ansible_facts["system"] == "Linux"
  ansible.builtin.shell:
    cmd: "echo ~{{ ansible_user }}"
  register: ansible_user_home
- name: Acquiring home of current user
  when: ansible_facts["system"] == "Linux"
  ansible.builtin.shell:
    cmd: "echo {{ ansible_user }}"
  register: current_user
- name: Informing user of requirement of two main domains 
  when: (certbot.domains | length) < 2 or (certbot.domains | length) > 2
  ansible.builtin.fail:
    msg: Only two domains allowed and required
- name: Informing user of requirement at least one wildcard
  when: (certbot.domains | select("regex", "^\\*\\.") | list | length) == 0
  ansible.builtin.fail:
    msg: At least one of the FQDNs must have a wildcard
# - name: Setting the FQDN for development
#   when: compose.mode == "dev"
#   ansible.builtin.set_fact:
#     web_fqdn: "{{ (certbot.domains | map('regex_replace', '\\.([^\\.]*)$', '.test') | reject('regex', '^\\*\\.') | list)[0] }}"
- name: Setting the FQDN for production
  # when: compose.mode == "prod"
  ansible.builtin.set_fact:
    web_fqdn: "{{ (certbot.domains | reject('regex', '^\\*\\.') | list)[0] }}"
- name: Moving git repository from initial path
  block:
    - name: Recursively copying directory and its contents to elsewhere
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.copy:
        src: "{{ ansible_user_home.stdout }}/repos/.foreign/{{ source_code.repos.compose.name }}"
        remote_src: true
        dest: "{{ ansible_user_home.stdout }}/repos/"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
      register: new_compose_path
    - name: Deleting directory at previous path
      ansible.builtin.file:
        path: "{{ ansible_user_home.stdout }}/repos/.foreign/{{ source_code.repos.compose.name }}"
        state: absent
    - name: Creating directory for new bare repository
      ansible.builtin.file:
        path: "{{ ansible_user_home.stdout }}/src"
        recurse: true
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        state: directory
    - name: Creating bare repository
      ansible.builtin.command:
        cmd: "git init --bare {{ source_code.repos.compose.name }}.git"
        chdir: "{{ ansible_user_home.stdout }}/src"
        creates: "{{ ansible_user_home.stdout }}/src/{{ source_code.repos.compose.name }}.git"
- name: Creating required SMTP-related container secret
  become: true
  # become_user: "{{ current_user.stdout }}"
  ansible.builtin.lineinfile:
    line: "{{ email.smtp.password }}"
    path: "{{ ansible_user_home.stdout }}/.podsecrets/email.pass"
    insertafter: EOF
    owner: "{{ ansible_user }}"
    group: "{{ ansible_user }}"
    mode: "644"
    create: true
    backup: true
- name: Creating environment file
  become: true
  become_user: "{{ current_user.stdout }}"
  ansible.builtin.template:
    src: user/all.env.j2
    dest: "{{ ansible_user_home.stdout }}/.all.env"
    owner: "{{ ansible_user }}"
    group: "{{ ansible_user }}"
    mode: "644"
    force: true
    backup: true
  register: environ
- name: Creating environment file for email
  become: true
  become_user: "{{ current_user.stdout }}"
  ansible.builtin.template:
    src: user/email.env.j2
    dest: "{{ ansible_user_home.stdout }}/.email.env"
    owner: "{{ ansible_user }}"
    group: "{{ ansible_user }}"
    mode: "644"
    force: true
    backup: true
  register: email_environ
- name: Creating a directory for container secrets
  ansible.builtin.file:
    path: "{{ ansible_user_home.stdout }}/.podsecrets"
    recurse: true
    owner: "{{ ansible_user }}"
    group: "{{ ansible_user }}"
    mode: "644"
    state: directory
- name: Creating directory for DBMS server configuration
  ansible.builtin.file:
    path: "{{ ansible_user_home.stdout }}/.config/{{ item }}"
    recurse: true
    owner: "{{ ansible_user }}"
    group: "{{ ansible_user }}"
    mode: "755"
    state: directory
  loop:
    - caddy
    - letsencrypt
    - mysql
    - redis
    - gitea
    - opengist
    - tailscale
    - glance
- name: Creating directory for main website root
  ansible.builtin.file:
    path: "{{ ansible_user_home.stdout }}/srv/{{ web_fqdn }}"
    recurse: true
    owner: "{{ ansible_user }}"
    group: "{{ ansible_user }}"
    mode: "755"
    state: directory
- name: Creating directory for caddy configuration
  ansible.builtin.file:
    path: "{{ ansible_user_home.stdout }}/.config/caddy"
    recurse: true
    owner: "{{ ansible_user }}"
    group: "{{ ansible_user }}"
    state: directory
# - name: Pulling all needed container images for Compose services
#   become: true
#   become_user: "{{ current_user.stdout }}"
#   ansible.builtin.command:
#     cmd: podman-compose pull
#     chdir: "{{ new_compose_path.dest }}{{ source_code.repos.compose.rpath | default('/independent') }}"
- name: Calculating desired container states
  block:
    - name: Calculating desired container state for VPN client
      ansible.builtin.set_fact:
        # @TODO write case of at least one vpn client having a boolean attribute declaring whether it is a container
        vpn_run: "{{ source_code.repos.compose.run and (vpn.clients | selectattr('name', 'in', web_fqdn) | length) == 1 and (compose.containers.vpn is defined and compose.containers.vpn != None) }}"
    - name: Calculating desired container state for web server or reverse proxy server
      ansible.builtin.set_fact:
        server_run: "{{ source_code.repos.compose.run and caddy.containerized and (compose.containers.webserver is defined and compose.containers.webserver != None) }}"
    - name: Calculatng desired container state for ACME challenge
      ansible.builtin.set_fact:
        ssl_run: "{{ server_run and certbot.containerized and (compose.containers.ssl is defined and compose.containers.ssl != None) }}"
    - name: Calculating desired container state for database management
      ansible.builtin.set_fact:
        dbms_run: "{{ source_code.repos.compose.run and mysql.containerized and (compose.containers.db is defined and compose.containers.db != None) }}"
    - name: Calculating desired container state for caching server
      ansible.builtin.set_fact:
        cache_run: "{{ source_code.repos.compose.run and redis.containerized and (compose.containers.cache is defined and compose.containers.cache != None) }}"
    - name: Calculating desired container state for cloud server
      ansible.builtin.set_fact:
        cloud_run: "{{ source_code.repos.compose.run and nextcloud.containerized and (compose.containers.cloud is defined and compose.containers.cloud != None) }}"
    - name: Calculating desired container state for forge server
      ansible.builtin.set_fact:
        forge_run: "{{ source_code.repos.compose.run and gitea.containerized and (compose.containers.forge is defined and compose.containers.forge != None ) }}"
    - name: Calculating desired container state for pastebin server
      ansible.builtin.set_fact:
        pbin_run: "{{ source_code.repos.compose.run and gist.containerized and (compose.containers.pastebin is defined and compose.containers.pastebin != None) }}"
    - name: Calculating desired container state for tailnet client
      ansible.builtin.set_fact:
        tail_run: "{{ source_code.repos.compose.run and tailscale.containerized and (compose.containers.tail is defined and compose.containers.tail != None) }}"
    - name: Calculating desired container state for tailnet dashboard
      ansible.builtin.set_fact:
        dash_run: "{{ source_code.repos.compose.run and glance.containerized and (compose.containers.dash is defined and compose.containers.dash != None) }}"
- name: Running VPN client Compose files
  when: vpn_run
  block:
    - name: Creating subdirectory for VPN client container specified by Compose file
      ansible.builtin.file:
        path: "{{ ansible_user_home.stdout }}/.wg/containerized"
        recurse: true
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        state: directory
    - name: Copying VPN client configuration files
      become: true
      become_user: "{{ current_user.stdout }}"
      when: item.name == inventory_hostname
      ansible.builtin.copy:
        src: "user/wg/containerized/{{ item.name }}{{ (idx | string) }}.conf"
        dest: "{{ ansible_user_home.stdout }}/.wg/containerized/"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
      loop: "{{ vpn.clients }}"
      loop_control:
        index_var: idx
    - name: Creating and deploying VPN client container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      when: source_code.repos.compose.run and (vpn.clients | selectattr("name", "in", web_fqdn) | length) == 1 and (compose.containers.vpn is defined and compose.containers.vpn != None)
      ansible.builtin.command:
        cmd: "podman-compose up -d {{ compose.containers.vpn.name }}"
        chdir: "{{ new_compose_path.dest }}{{ source_code.repos.compose.rpath | default('/independent') }}"
    - name: Opening port 51820
      become: true
      ansible.builtin.iptables:
        chain: INPUT
        protocol: "{{ item }}"
        destination_port: 51820
        jump: ACCEPT
        comment: Open up port 51820
      loop:
        - udp
        - tcp
- name: Spinning up database management container specified by Compose file
  when: dbms_run
  block:
    - name: Creating required container secret for DBMS server container's root account
      become: true
      # become_user: "{{ current_user.stdout }}"
      ansible.builtin.lineinfile:
        line: "{{ mysql.password }}"
        path: "{{ ansible_user_home.stdout }}/.podsecrets/root-mysql.pass"
        insertafter: EOF
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        create: true
        backup: true
    - name: Creatng required container secret for DBMS server container's primary non-root account
      become: true
      # become_user: "{{ current_user.stdout }}"
      ansible.builtin.lineinfile:
        line: "{{ mysql.users.admin.password }}"
        path: "{{ ansible_user_home.stdout }}/.podsecrets/user-mysql.pass"
        insertafter: EOF
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        create: true
        backup: true
    - name: Creating environment file for DBMS server container specified in Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.template:
        src: user/mysql.env.j2
        dest: "{{ ansible_user_home.stdout }}/.mysql.env"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
      register: mysql_environ
    - name: Creating and deploying DBMS server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.command:
        cmd: "podman-compose --env-file {{ mysql_environ.dest }} --env-file {{ environ.dest }} up -d {{ compose.containers.db.name }}"
        chdir: "{{ new_compose_path.dest }}{{ source_code.repos.compose.rpath | default('/independent') }}"
        # @TODO see if manual creation of additional databases is necessary for the DBMS server container
        # REDIS
- name: Spinning up caching container specified by Compose file
  when: cache_run
  block:
    - name: Creating environment file for DBMS server container specified in Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.template:
        src: user/redis.env.j2
        dest: "{{ ansible_user_home.stdout }}/.redis.env"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
      register: redis_environ
    - name: Creating and deploying cache server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.command:
        cmd: "podman-compose --env-file {{ environ.dest }} up -d {{ compose.containers.cache.name }}"
        chdir: "{{ new_compose_path.dest }}{{ source_code.repos.compose.rpath | default('/independent') }}"
- name: Spinning up cloud container specified by Compose file
  when: cloud_run
  block:
    - name: Creating database necessary for cloud server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      when: dbms_run
      containers.podman.podman_container_exec:
        name: "{{ compose.containers.db.name }}"
        argv: 
          - mysql
          - "-u"
          - "{{ mysql.users.admin.username }}"
          - "-p{{ mysql.users.admin.password }}"
          - "-e"
          - "'CREATE DATABASE IF NOT EXISTS {{ mysql.users.admin.databases.nextcloud.name }};'"
        detach: true
    - name: Creating required cache-related container secret for cloud server container specified by Compose file
      become: true
      # become_user: "{{ current_user.stdout }}"
      when: cache_run
      ansible.builtin.lineinfile:
        line: "{{ redis.password }}"
        dest: "{{ ansible_user_home.stdout }}/.podsecrets/redis.pass"
        insertafter: EOF
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        create: true
        backup: true
    - name: Creating environment file for cloud server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.template:
        src: user/nextcloud.env.j2
        dest: "{{ ansible_user_home.stdout }}/.nextcloud.env"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
      register: nextcloud_environ
    - name: Creating and deploying DBMS server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.command:
        cmd: "podman-compose --env-file {{ mysql_environ.dest }} --env-file {{ email_environ.dest }} --env-file {{ nextcloud_environ.dest }} --env-file {{ environ.dest }} up -d {{ compose.containers.cloud.name }}"
        chdir: "{{ new_compose_path.dest }}{{ source_code.repos.compose.rpath | default('/independent') }}"
    - name: Adding Caddyfile subdomain entry
      when: "server_run and mode == 'prod'"
      ansible.builtin.blockinfile:
        path: "{{ ansible_user_home.stdout }}/.config/caddy/Caddyfile"
        block: |
          {{ nextcloud.subdomain }}.{{ web_fqdn }} {
              root /srv/{{ nextcloud.subdomain }}.{{ web_fqdn }}
              file_server
              php_fastcgi localhost:9000

              handle_errors {
                root /srv/{{ web_fqdn }}
                rewrite /error/{err.status_code}.html
                templates
                encode gzip
              }
          }
        prepend_newline: true
        marker: "# <-- {mark} ANSIBLE MANAGED CLOUD DOMAIN -->"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        create: true
        mode: "644"
        state: present
    - name: Adding Caddyfile subdomain entry
      when: "server_run and (mode == 'dev' or caddy.scheme == 'http')"
      ansible.builtin.blockinfile:
        path: "{{ ansible_user_home.stdout }}/.config/caddy/Caddyfile"
        block: |
          http://{{ nextcloud.subdomain }}.{{ web_fqdn }} {
              root /srv/{{ nextcloud.subdomain }}.{{ web_fqdn }}
              file_server
              php_fastcgi localhost:9000

              handle_errors {
                root /srv/{{ web_fqdn }}
                rewrite /error/{err.status_code}.html
                templates
                encode gzip
              }
          }
        prepend_newline: true
        marker: "# <-- {mark} ANSIBLE MANAGED CLOUD DOMAIN -->"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        create: true
        mode: "644"
        state: present
    # - name: Restarting webserver / reverse proxy container
    #   become: true
    #   become_user: "{{ current_user.stdout }}"
    #   when: server_run
    #   containers.podman.podman_container:
    #     name: "{{ compose.containers.webserver.name }}"
    #     state: started
    #     force_restart: true
- name: Spinning up forge container specified by Compose file
  when: forge_run
  block:
    - name: Creating database necessary for forge server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      when: dbms_run
      containers.podman.podman_container_exec:
        name: "{{ compose.containers.db.name }}"
        argv: 
          - mysql
          - "-u"
          - "{{ mysql.users.admin.username }}"
          - "-p{{ mysql.users.admin.password }}"
          - "-e"
          - "'CREATE DATABASE IF NOT EXISTS {{ mysql.users.admin.databases.gitea.name }};'"
        detach: true
    - name: Creating environment file for forge server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.template:
        src: user/gitea.env.j2
        dest: "{{ ansible_user_home.stdout }}/.gitea.env"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
      register: gitea_environ
    - name: Creating and deploying forge server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.command:
        cmd: "podman-compose --env-file {{ mysql_environ.dest }} --env-file {{ email_environ.dest }} --env-file {{ gitea_environ.dest }} --env-file {{ environ.dest }} up -d {{ compose.containers.forge.name }}"
        chdir: "{{ new_compose_path.dest }}{{ source_code.repos.compose.rpath | default('/independent') }}"
    - name: Adding Caddyfile subdomain entry
      when: "server_run and mode == 'prod'"
      ansible.builtin.blockinfile:
        path: "{{ ansible_user_home.stdout }}/.config/caddy/Caddyfile"
        block: |
          {{ gitea.subdomain }}.{{ web_fqdn }} {
              reverse_proxy localhost:3000

              handle_errors {
                root /srv/{{ web_fqdn }}
                rewrite /error/{err.status_code}.html
                file_server
                templates
                encode gzip
              }
          }
        prepend_newline: true
        marker: "# <-- {mark} ANSIBLE MANAGED CLOUD DOMAIN -->"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        create: true
        mode: "644"
        state: present
    - name: Adding Caddyfile subdomain entry
      when: "server_run and (mode == 'dev' or caddy.scheme == 'http')"
      ansible.builtin.blockinfile:
        path: "{{ ansible_user_home.stdout }}/.config/caddy/Caddyfile"
        block: |
          http://{{ gitea.subdomain }}.{{ web_fqdn }} {
              reverse_proxy localhost:3000

              handle_errors {
                root /srv/{{ web_fqdn }}
                rewrite /error/{err.status_code}.html
                file_server
                templates
                encode gzip
              }
          }
        prepend_newline: true
        marker: "# <-- {mark} ANSIBLE MANAGED CLOUD DOMAIN -->"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        create: true
        mode: "644"
        state: present
    # - name: Restarting webserver / reverse proxy container
    #   become: true
    #   become_user: "{{ current_user.stdout }}"
    #   when: server_run
    #   containers.podman.podman_container:
    #     name: "{{ compose.containers.webserver.name }}"
    #     state: started
    #     force_restart: true
- name: Spinning up pastebin container specified by Compose file
  when: pbin_run
  block:
    - name: Creating database necessary for pastebin server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      when: dbms_run
      containers.podman.podman_container_exec:
        name: "{{ compose.containers.db.name }}"
        argv: 
          - mysql
          - "-u"
          - "{{ mysql.users.admin.username }}"
          - "-p{{ mysql.users.admin.password }}"
          - "-e"
          - "'CREATE DATABASE IF NOT EXISTS {{ mysql.users.admin.databases.opengist.name }};'"
        detach: true
    - name: Creating environment file for pastebin server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      when: pbin_run
      ansible.builtin.template:
        src: user/opengist.env.j2
        dest: "{{ ansible_user_home.stdout }}/.opengist.env"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
      register: opengist_environ
    - name: Creating gist configuration file
      become: true
      become_user: "{{ current_user.stdout }}"
      when: pbin_run
      ansible.builtin.template:
        src: user/config/opengist/config.yml.j2
        dest: "{{ ansible_user_home.stdout }}/.config/opengist/config.yml"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
    - name: Creating and deploying pastebin server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      when: pbin_run
      ansible.builtin.command:
        cmd: "podman-compose --env-file {{ opengist_environ.dest }} --env-file {{ mysql_environ.dest }} --env-file {{ environ.dest }} up -d {{ compose.containers.pastebin.name }}"
        chdir: "{{ new_compose_path.dest }}{{ source_code.repos.compose.rpath | default('/independent') }}"
    - name: Adding Caddyfile subdomain entry
      when: "server_run and mode == 'prod'"
      ansible.builtin.blockinfile:
        path: "{{ ansible_user_home.stdout }}/.config/caddy/Caddyfile"
        block: |
          {{ gist.subdomain }}.{{ web_fqdn }} {
              reverse_proxy localhost:6157

              handle_errors {
                root /srv/{{ web_fqdn }}
                rewrite /error/{err.status_code}.html
                file_server
                templates
                encode gzip
              }
          }
        prepend_newline: true
        marker: "# <-- {mark} ANSIBLE MANAGED CLOUD DOMAIN -->"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        create: true
        mode: "644"
        state: present
    - name: Adding Caddyfile subdomain entry
      when: "server_run and (mode == 'dev' or caddy.scheme == 'http')"
      ansible.builtin.blockinfile:
        path: "{{ ansible_user_home.stdout }}/.config/caddy/Caddyfile"
        block: |
          http://{{ gist.subdomain }}.{{ web_fqdn }} {
              reverse_proxy localhost:6157

              handle_errors {
                root /srv/{{ web_fqdn }}
                rewrite /error/{err.status_code}.html
                file_server
                templates
                encode gzip
              }
          }
        prepend_newline: true
        marker: "# <-- {mark} ANSIBLE MANAGED CLOUD DOMAIN -->"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        create: true
        mode: "644"
        state: present
    # - name: Restarting webserver / reverse proxy container
    #   become: true
    #   become_user: "{{ current_user.stdout }}"
    #   when: server_run
    #   containers.podman.podman_container:
    #     name: "{{ compose.containers.webserver.name }}"
    #     state: started
    #     force_restart: true
- name: Spinning up web or reverse proxy server container specified by Compose file
  when: server_run
  block:
    - name: Creating directory for website subdomains
      ansible.builtin.file:
        path: "{{ ansible_user_home.stdout }}/srv/{{ item }}.{{ web_fqdn }}"
        recurse: true
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        state: directory
      loop:
        - certbot
        - notes
        - blog
    - name: Creating directory for Caddy configuration
      ansible.builtin.file:
        path: "{{ ansible_user_home.stdout }}/.caddy"
        recurse: true
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        state: directory
    - name: Creating and deploying webserver / reverse proxy server container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.command:
        cmd: "podman-compose --env-file {{ environ.dest }} up -d {{ compose.containers.webserver.name }}"
        chdir: "{{ new_compose_path.dest }}{{ source_code.repos.compose.rpath | default('/independent') }}"
    - name: Creating volume subdirectory for main website root's error pages
      ansible.builtin.file:
        path: "{{ ansible_user_home.stdout }}/srv/{{ web_fqdn }}/error"
        recurse: true
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        state: directory
    - name: Creating image files for main website root's error path
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.copy:
        src: "user/srv/domain-root/error/{{ item }}"
        dest: "{{ ansible_user_home.stdout }}/srv/{{ web_fqdn }}/error/"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        backup: true
        mode: "644"
      loop:
        - 503.html
        - "mythe-sisyphus-klein.png"
        - "dark-matter.png"
    - name: Creating or updating Caddyfile at directory
      when: "mode == 'prod' and ssl_run"
      ansible.builtin.blockinfile:
        path: "{{ ansible_user_home.stdout }}/.config/caddy/Caddyfile"
        block: |
          http://{{ web_fqdn }} {
              handle /.well-known/acme-challenge/* {
                reverse_proxy localhost:80
              }
              handle {
                redir https://{host}{uri} 308
              }
          }
          :80 {
            root /srv/certbot.{{ web_fqdn }}
            browse
          }
          {{ web_fqdn }} {
              respond 503
              # root /srv/{{ web_fqdn }}
              file_server
              
              header /.well-known/openpgpkey/* {
                Content-Type application/octet-stream
                Access-Control-Allow-Origin *
              }
              
              handle_errors {
                rewrite /error/{err.status_code}.html
                templates
              }
          }
        prepend_newline: true
        marker: "# <-- {mark} ANSIBLE MANAGED ROOT DOMAIN -->"
        create: true
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        state: present
    - name: Creating or updating Caddyfile at directory
      when: "mode == 'prod' and not ssl_run"
      ansible.builtin.blockinfile:
        path: "{{ ansible_user_home.stdout }}/.config/caddy/Caddyfile"
        block: |
          {{ web_fqdn }} {
              respond 503
              # root /srv/{{ web_fqdn }}
              file_server
              
              header /.well-known/openpgpkey/* {
                Content-Type application/octet-stream
                Access-Control-Allow-Origin *
              }
              
              handle_errors {
                rewrite /error/{err.status_code}.html
                templates
              }
          }
        prepend_newline: true
        marker: "# <-- {mark} ANSIBLE MANAGED ROOT DOMAIN -->"
        create: true
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        state: present
    - name: Creating or updating Caddyfile at directory
      when: "mode == 'dev' or caddy.scheme == 'http'"
      ansible.builtin.blockinfile:
        path: "{{ ansible_user_home.stdout }}/.config/caddy/Caddyfile"
        block: |
          http://{{ web_fqdn }} {
              respond 503
              # root /srv/{{ web_fqdn }}
              file_server
              
              header /.well-known/openpgpkey/* {
                Content-Type application/octet-stream
                Access-Control-Allow-Origin *
              }
              
              handle_errors {
                rewrite /error/{err.status_code}.html
                templates
              }
          }
        prepend_newline: true
        marker: "# <-- {mark} ANSIBLE MANAGED ROOT DOMAIN -->"
        create: true
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        state: present
    - name: Opening port 443
      become: true
      ansible.builtin.iptables:
        chain: INPUT
        protocol: "{{ item }}"
        destination_port: 443
        jump: ACCEPT
        comment: Open up port 443
      loop:
        - udp
        - tcp
    - name: Opening ports
      become: true
      ansible.builtin.iptables:
        chain: INPUT
        protocol: tcp
        destination_port: "{{ item }}"
        jump: ACCEPT
        comment: "Open up port {{ (item | string) }}"
      loop:
        - 80
    # - name: Restarting webserver / reverse proxy container
    #   become: true
    #   become_user: "{{ current_user.stdout }}"
    #   containers.podman.podman_container:
    #     name: "{{ compose.containers.webserver.name }}"
    #     state: started
    #     force_restart: true
- name: Spinning up ACME challenge container specified by Compose file
  when: ssl_run
  ignore_errors: true
  block:
    - name: Creating environment file for SSL/TLS certificate acquisition container specified in Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.template:
        src: user/certbot.env.j2
        dest: "{{ ansible_user_home.stdout }}/.certbot.env"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
      register: certbot_environ
    - name: Creating and deploying SSL/TLS certificate acquisition container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.command:
        cmd: "podman-compose --env-file {{ certbot_environ.dest }} --env-file {{ environ.dest }} up -d {{ compose.containers.ssl.name }}"
        chdir: "{{ new_compose_path.dest }}{{ source_code.repos.compose.rpath | default('/independent') }}"
- name: Spinning up tailnet container specified by Compose file
  when: tail_run
  block:
    - name: Creating required tailnet container secret for tailnet container specified by Compose file
      become: true
      # become_user: "{{ current_user.stdout }}"
      when: item.name == inventory_hostname
      ansible.builtin.copy:
        src: "{{ item.name }}-{{ headscale.users.admin.username }}@headscale/headscale{{ (idx | string) }}.key"
        dest: "{{ ansible_user_home.stdout }}/.podsecrets/headscale.key"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
      loop: "{{ headscale.clients }}"
      loop_control:
        index_var: idx
    - name: Creating tailnet configuration file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.template:
        src: user/config/tailscale/conf.json.j2
        dest: "{{ ansible_user_home.stdout }}/.config/tailscale/conf.json"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
    - name: Creating and deploying tailnet container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.command:
        cmd: "podman-compose --env-file {{ environ.dest }} up -d {{ compose.containers.tail.name }}"
        chdir: "{{ new_compose_path.dest }}{{ source_code.repos.compose.rpath | default('/independent') }}"
- name: Spinning up dashboard container specified by Compose file
  when: tail_run and dash_run
  block:
    - name: Creating glance configuration file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.template:
        src: user/config/glance/glance.yml.j2
        dest: "{{ ansible_user_home.stdout }}/.config/glance/glance.yml"
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "644"
        force: true
        backup: true
    - name: Creating and deploying dashboard container specified by Compose file
      become: true
      become_user: "{{ current_user.stdout }}"
      ansible.builtin.command:
        cmd: "podman-compose up -d {{ compose.containers.dash.name }}"
        chdir: "{{ new_compose_path.dest }}{{ source_code.repos.compose.rpath | default('/independent') }}"
- name: Restarting webserver / reverse proxy container
  become: true
  become_user: "{{ current_user.stdout }}"
  when: server_run
  containers.podman.podman_container:
    name: "{{ compose.containers.webserver.name }}"
    state: started
    force_restart: true
- name: Making running containers persist on user logout
  become: true
  ansible.builtin.shell:
    cmd: loginctl enable-linger $(whoami)

