- name: Postgres key
  apt_key:
    data: |
        -----BEGIN PGP PUBLIC KEY BLOCK-----

[encoded data, 5256 characters]
        Gtz3cydIohvNO9d90+29h0eGEDYti7j7maHkBKUAwlcPvMg5m3Y=
        =DA1T
        -----END PGP PUBLIC KEY BLOCK-----


- name: Postgres repo
  apt_repository:
    repo: deb http://apt.postgresql.org/pub/repos/apt bullseye-pgdg main
    filename: postgres

- block:
    - name: Postgres server
      apt:
        pkg:
          - postgresql-12
          - libpq-dev
        default_release: bullseye-pgdg

    - name: Postgres disable default server
      systemd:
        enabled: False
        state: stopped
        masked: True
        name: postgresql@12-main.service


    - name: New Postgres service
      template:
        src: postgresql.service.j2
        dest: /etc/systemd/system/postgresql.service
      register: postgresql_service_changed

    - name: Check if Postgres is created
      stat:
        path: '{{postgres_server_root}}'
      register: postgres_server_created

    - block:
      - name: 'Create {{postgres_server_root}}'
        file:
          path: '{{postgres_server_root}}'
          state: directory
          owner: postgres
          group: postgres
          mode: '0755'

      - name: Init postgres
        command:
          cmd: '/usr/lib/postgresql/12/bin/initdb --locale=en_US.UTF-8 -E UTF8  -D {{postgres_server_root}}/data'
          chdir: '{{postgres_server_root}}'
        become: True
        become_user: postgres
      when: not postgres_server_created.stat.exists

    - block:
      - name: Stop old service
        systemd:
            enabled: False
            state: stopped
            name: postgresql.service

      - name: Reload systemd
        systemd:
          daemon_reload: True
      when: postgresql_service_changed.changed

    - name: Start postgres service
      systemd:
        enabled: True
        state: started
        name: postgresql.service

    - name: Psycopg2 for the sake of ansible
      apt:
        pkg:
          - python3-psycopg2
  when: postgres_server

- name: Postgres
  apt:
    pkg:
      - postgresql-client-12
      - libpq-dev
    default_release: bullseye-pgdg
  when: postgres_client

