---
- name: Verify if postgresql_password is set
  assert:
    that: postgresql_password is defined
    fail_msg: >-
      You must define postgresql_password variable to be able accessing
      the database.

- name: Copy SQL file on the host
  block:
    - name: Create a tempfile for the SQL file on the host
      tempfile:
        state: file
      register: __postgresql_sql_tempfile
      changed_when: false

    - name: Copy the sql input file to the host {{ postgresql_input_file }}
      copy:
        src: "{{ postgresql_input_file }}"
        dest: "{{ __postgresql_sql_tempfile.path }}"
        owner: postgres
        group: postgres
        mode: '0600'
      changed_when: false

- name: Input sql file to PostgreSQL {{ postgresql_input_file }}
  block:
    - name: Run SQL script
      become: true
      become_user: postgres
      environment:
        PGPASSWORD: "{{ postgresql_password }}"
      command:
        cmd: psql -U postgres -f "{{ __postgresql_sql_tempfile.path }}"
      register: __postgresql_output
      changed_when: false
  always:
    - name: Print the output of psql command for {{ postgresql_input_file }}
      debug:
        msg: "{{ __postgresql_output }}"

- name: Remove sql script from the host {{ postgresql_input_file }}
  file:
    state: absent
    path: "{{ __postgresql_sql_tempfile.path }}"
