- name: mastodon | postgres | Create database {{ mastodon_db }}
  postgresql_db:
    name: "{{ mastodon_db }}"
    login_host: "{{ mastodon_db_login_host }}"
    login_password: "{{ mastodon_db_login_password }}"
    login_user: "{{ mastodon_db_login_user }}"
    port: "{{ mastodon_db_port }}"
  register: create_remote_db
  when:
    - mastodon_db_login_user is defined
    - mastodon_db_login_host is defined
    - mastodon_db_login_password is defined
    - mastodon_db_port is defined

- name: mastodon | postgres | Create database user {{ mastodon_db_user }}
  postgresql_user:
    db: "{{ mastodon_db }}"
    name: "{{ mastodon_db_user }}"
    password: "{{ mastodon_db_password }}"
    login_host: "{{ mastodon_db_login_host }}"
    login_password: "{{ mastodon_db_login_password }}"
    login_user: "{{ mastodon_db_login_user }}"
    port: "{{ mastodon_db_port }}"
    role_attr_flags: CREATEDB
  register: create_remote_db_user
  when:
    - mastodon_db_login_user is defined
    - mastodon_db_login_host is defined
    - mastodon_db_login_password is defined
    - mastodon_db_port is defined

- name: mastodon | postgres | Create database {{ mastodon_db }}
  postgresql_db:
    name: "{{ mastodon_db }}"
    login_unix_socket: "{{ mastodon_db_login_unix_socket }}"
  register: create_local_db
  become: true
  become_user: "postgres"
  when: create_remote_db is skipped

- name: mastodon | postgres | Create database user {{ mastodon_db_user }}
  postgresql_user:
    db: "{{ mastodon_db }}"
    name: "{{ mastodon_db_user }}"
    password: "{{ mastodon_db_password | default('') }}"
    encrypted: yes
    login_unix_socket: "{{ mastodon_db_login_unix_socket }}"
    role_attr_flags: CREATEDB
  become: true
  become_user: "postgres"
  when: create_remote_db_user is skipped