---
- hosts:
    - knot
  vars:
    wal_g: /etc/postgresql/wal-g.env
    wal_g_bin: /var/lib/postgresql/wal-g
    pg_v: 15
  tasks:
    - name: "mkdir {{ wal_g }}"
      become: yes
      file:
        path: "{{ wal_g }}"
        state: directory
        mode: ug=rx,o=
        owner: root
        group: postgres


    - name: Load values from../knot-pdb.sops.yml
      community.sops.load_vars:
        name: env
        file: ../knot-pdb.sops.yml

    - name: Configure environment
      become: yes
      tags: env
      copy:
        dest: "{{ wal_g }}/{{ item.file }}"
        content: |
          {{ item.content }}
        owner: root
        group: postgres
        mode: g=r,u=r,o=
      loop:
        - {file: "AWS_ACCESS_KEY_ID", content: "{{ env.AWS_ACCESS_KEY_ID }}"}
        - {file: "AWS_ENDPOINT", content: "{{ env.AWS_ENDPOINT }}"}
        - {file: "AWS_REGION", content: "{{ env.AWS_REGION }}"}
        - {file: "AWS_S3_FORCE_PATH_STYLE", content: "{{ env.AWS_S3_FORCE_PATH_STYLE }}"}
        - {file: "AWS_SECRET_ACCESS_KEY", content: "{{ env.AWS_SECRET_ACCESS_KEY }}"}
        - {file: "WALG_S3_PREFIX", content: "{{ env.WALG_S3_PREFIX }}"}
        - {file: "PGHOST", content: "/var/run/postgresql"}

    - name: /etc/postgresql/{{ pg_v }}/main/wal-g.conf
      become: yes
      copy:
        dest: /etc/postgresql/{{ pg_v }}/main/wal-g.conf
        content: |
         archive_mode = yes
         archive_command = '/usr/bin/envdir {{ wal_g }} {{ wal_g_bin }} wal-push %p'
         archive_timeout = 60

    - name: /etc/postgresql/{{ pg_v }}/main/postgresql.conf
      become: yes
      lineinfile:
        path: /etc/postgresql/{{ pg_v }}/main/postgresql.conf
        regexp: listen_addresses
        line: "listen_addresses = '127.0.0.1,10.0.3.1,fdf3:aad9:a885:b3a::1'"

    - name: /etc/postgresql/{{ pg_v }}/main/postgresql.conf
      become: yes
      lineinfile:
        path: /etc/postgresql/{{ pg_v }}/main/postgresql.conf
        regexp: wal-g.conf
        line: "include = 'wal-g.conf'"

    - name: /etc/postgresql/{{ pg_v }}/main/pg_hba.conf
      become: yes
      lineinfile:
        path: /etc/postgresql/{{ pg_v }}/main/pg_hba.conf
        regexp: fdf3:aad9:a885:b3a
        line: "host all all fdf3:aad9:a885:b3a::/64 scram-sha-256"