---
  # "Create the database, import the dumped data and reindex."

  - name: "Check if the {{ fwd_db_name }} database instance exists (PostgreSQL)."
    shell: psql -lqt | cut -d \| -f 1 | grep -qw "{{ fwd_db_name }}"
    become_method: sudo
    become_user: postgres
    register: pg_db_exists
    ignore_errors: true
    changed_when: false
    when: fwd_import_db|bool and pg_mode|bool

  - name: "Substitute {{ db_port }} for PG_PORT in build.properties."
    replace:
       dest: "{{ fwd_install_root }}{{ fwd_app_name }}/build.properties"
       regexp: "PG_PORT"
       replace: "{{ db_port }}"
    when: pg_mode|bool
  
  - name: "Check if the {{ fwd_db_name }} database instance exists (H2)."
    find:
       paths: "{{ fwd_install_root }}/{{ fwd_app_name }}/deploy/db/"
    register: h2_db_exists
    changed_when: false
    when: fwd_import_db|bool and not (pg_mode|bool)

  - name: "Check if the data dump files exist."
    find:
       paths: "{{ fwd_install_root }}/{{ fwd_app_name }}/data/dump/{{ fwd_db_name }}/"
    register: dump_files
    changed_when: false

  - name: "Check if the data dump zip file exists."
    stat:
       path: "{{ fwd_install_root }}/{{ fwd_app_data_dump_zip }}"
    register: dump_zip_file
    changed_when: false

  - name: "Unzip the data dump files."
    command: unzip -q -o "{{ fwd_install_root }}/{{ fwd_app_data_dump_zip }}" -d "{{ fwd_install_root }}/{{ fwd_app_name }}/data/dump/{{ fwd_db_name }}/"
    args:
       chdir: "{{ fwd_install_root }}/{{ fwd_app_name }}/"
    register: dump_unzipped
    when: dump_zip_file.stat.exists and dump_files.matched|int == 0

  - name: "Create the database, import the dumped data and reindex."
    command: ant import.db
    args:
       chdir: "{{ fwd_install_root }}/{{ fwd_app_name }}/"
    register: import_result
    when: fwd_import_db|bool and ((pg_mode|bool and pg_db_exists.rc == 1) or (not (pg_mode|bool) and h2_db_exists.matched|int == 0))

  - name: "Remove the data dump files."
    shell: rm -fr "{{ fwd_install_root }}/{{ fwd_app_name }}/data/dump/*"
    when: fwd_import_db|bool and import_result.changed and import_result|success

  - name: "Ensure that the ownership and permissions are correct for the deploy/db folder." 
    file:
       path: "{{ fwd_install_root }}/{{ fwd_app_name }}/deploy/db/"
       state: directory
       follow: no
       recurse: yes
       owner: "{{ fwd_acct_name }}"
       group: "{{ fwd_acct_name }}"
       mode: 0775
    when: fwd_import_db|bool and not (pg_mode|bool)
