- name: ensure packages required for resultsdb are installed
  action: yum name={{ item }} state=latest
  when: deployment_type == 'prod' or deployment_type == 'local'
  with_items:
    - resultsdb
    - mod_wsgi
    - python-psycopg2
    - libsemanage-python

- name: ensure packages required for resultsdb are installed (infra-testing)
  action: yum name={{ item }} state=latest enablerepo=infrastructure-testing
  when: deployment_type == 'dev' or deployment_type == 'stg'
  with_items:
    - resultsdb
    - mod_wsgi
    - python-psycopg2
    - libsemanage-python

- name: ensure database is created
  delegate_to: "{{ resultsdb_db_host }}"
  sudo_user: postgres
  sudo: true
  action: postgresql_db db={{ resultsdb_db_name }}

- name: ensure dev resultsdb db user has access to dev database
  when: deployment_type == 'dev'
  delegate_to: "{{ resultsdb_db_host }}"
  sudo_user: postgres
  sudo: true
  action: postgresql_user db={{ resultsdb_db_name }} user={{ dev_resultsdb_db_user }} password={{ dev_resultsdb_db_password }} role_attr_flags=NOSUPERUSER

- name: ensure stg resultsdb db user has access to stg database
  when: deployment_type == 'stg'
  delegate_to: "{{ resultsdb_db_host }}"
  sudo_user: postgres
  sudo: true
  action: postgresql_user db={{ resultsdb_db_name }} user={{ stg_resultsdb_db_user }} password={{ stg_resultsdb_db_password }} role_attr_flags=NOSUPERUSER

- name: ensure prod resultsdb db user has access to prod database
  when: deployment_type == 'prod'
  delegate_to: "{{ resultsdb_db_host }}"
  sudo_user: postgres
  sudo: true
  action: postgresql_user db={{ resultsdb_db_name }} user={{ prod_resultsdb_db_user }} password={{ prod_resultsdb_db_password }} role_attr_flags=NOSUPERUSER

- name: ensure local resultsdb db user has access to prod database
  when: deployment_type == 'local'
  delegate_to: "{{ resultsdb_db_host }}"
  sudo_user: postgres
  sudo: true
  action: postgresql_user db={{ resultsdb_db_name }} user={{ local_resultsdb_db_user }} password={{ local_resultsdb_db_password }} role_attr_flags=NOSUPERUSER

- name: ensure selinux lets httpd talk to postgres
  seboolean: name=httpd_can_network_connect_db persistent=yes state=yes

- name: generate resultsdb config
  template: src=settings.py.j2 dest=/etc/resultsdb/settings.py owner=root group=root mode=0644
  notify:
    - restart httpd

- name: generate resultsdb apache config
  template: src=resultsdb.conf.j2 dest=/etc/httpd/conf.d/resultsdb.conf owner=root group=root mode=0644
  notify:
    - restart httpd

# this command will clear the exising database and it's now being run every time, regardless of whether
# /etc/resultsdb-is-init exists or not. We've already lost a lot of data, so commenting this command out
# while we figure out how to handle the problem
#- name: initialize resultsdb database
#  shell: PROD='true' resultsdb init_db && touch /etc/resultsdb/db-is-init creates=/etc/resultsdb-is-init 
