---
- hosts: localhost
  gather_facts: false
  environment:
    KUBECONFIG: "{{ kubeconfig_path }}"
  vars:
    db_path: []
  tasks:
    - debug:
        var: migration_versions
    - block:
      - name: generating migration db paths
        set_fact:
          db_path: "{{ db_path }} + [ '{{playbook_dir}}/db/init_dbs/postgresql/{{ item }}/*.sql' ]" 
        with_items: "{{ migration_versions.split(',') }}"
      - name: Migrate postgresql
        shell: |
          file="{{ item|basename }}"
          kubectl exec -n db postgresql-postgresql-0 -- /bin/bash -c "rm -rf /tmp/$file"
          kubectl cp -n db {{ item }} postgresql-postgresql-0:/tmp/
          kubectl exec -n db postgresql-postgresql-0 -- /bin/bash -c "PGPASSWORD=asayerPostgres psql -U postgres -f /tmp/$file" &> "{{ playbook_dir }}"/postgresql_init.log
        args:
          chdir: db/init_dbs/postgresql
        with_fileglob: "{{ db_path }}"
      tags:
        - postgresql
    - block:
      - name: Resetting the db path
        set_fact:
          db_path: []
      - name: generating migration db paths
        set_fact:
          db_path: "{{dst_list | default([])}} + [ '{{ item[0] }}/*.sql' ]" 
        with_items: "{{ migration_versions.split(',') }}"
      - name: Restoring clickhouse data
        shell: |
          file="{{ item|basename }}"
          kubectl exec -n db clickhouse-0 -- /bin/bash -c "rm -rf /tmp/$file"
          kubectl cp -n db $file clickhouse-0:/tmp/
          kubectl exec -n db clickhouse-0 -- /bin/bash -c "clickhouse-client < /tmp/$file" 2>&1 | tee -a "{{ playbook_dir }}"/clickhouse_init.log
        args:
          chdir: db/init_dbs/clickhouse/create
        with_fileglob:
          - "{{ db_path }}"
        retries: 3
        delay: 60
        register: result
        until: result.rc == 0
      tags:
        - clickhouse
      when: enterprise_edition_license|length > 0
