# This playbook is used to rebuild staging Koschei database.
# Useful to be ran after synchronization of staging Koji DB
# with production, which breaks Koschei - old builds from before sync
# have conflicting IDs with post-sync builds.
#
# In future, this playbook may be extended to sync content from
# production Koschei database dump, but this is not needed for now.

- name: sync staging Koschei with production
  hosts: os_control_stg[0]
  user: root
  vars_files:
   - /srv/web/infra/ansible/vars/global.yml
   - /srv/private/ansible/vars.yml
   - /srv/web/infra/ansible/vars/{{ ansible_distribution }}.yml
   - /srv/web/infra/ansible/roles/openshift-apps/koschei/vars/main.yml
   - /srv/web/infra/ansible/roles/openshift-apps/koschei/vars/{{ env }}.yml
  handlers:
  - import_tasks: "{{ handlers_path }}/restart_services.yml"

  tasks:
  - name: Stop backend services
    shell: oc -n koschei scale dc/{{item.name}} --replicas=0
    with_items: "{{ koschei_backend_services }}"
    loop_control:
      label: "{{ item.name }}"

  - name: Stop frontend
    shell: oc -n koschei scale dc/frontend --replicas=0

  - name: Drop koschei database
    postgresql_db: name=koschei state=absent
    become: yes
    become_user: postgres
    delegate_to: "{{ koschei_pgsql_hostname }}"

  - name: Create empty koschei database
    postgresql_db: name=koschei owner=koscheiadmin
    become: yes
    become_user: postgres
    delegate_to: "{{ koschei_pgsql_hostname }}"

  - name: Populate koschei database with schema and initial data
    include_role: name=openshift-apps/koschei/job
    vars:
      name: db-create
      command: "koschei-admin create-db && koschei-admin create-collection f37 --display-name 'Fedora Rawhide' --target f37 --bugzilla-product Fedora --bugzilla-version rawhide && koschei-admin create-group php"

  - name: Start frontend
    shell: oc -n koschei scale dc/frontend --replicas={{koschei_frontend_replicas}}

  - name: Start backend services
    shell: oc -n koschei scale dc/{{item.name}} --replicas=1
    with_items: "{{ koschei_backend_services }}"
    loop_control:
      label: "{{ item.name }}"
