---
- name: Save etcd snapshot
  command: "{{ bin_dir }}/etcdctl snapshot save /tmp/snapshot.db"
  environment:
    ETCDCTL_CERT: "{{ etcd_cert_dir }}/admin-{{ inventory_hostname }}.pem"
    ETCDCTL_KEY: "{{ etcd_cert_dir }}/admin-{{ inventory_hostname }}-key.pem"
    ETCDCTL_CACERT: "{{ etcd_cert_dir }}/ca.pem"
    ETCDCTL_ENDPOINTS: "{{ etcd_access_addresses.split(',') | first }}"
    ETCDCTL_API: "3"
  when: etcd_snapshot is not defined

- name: Transfer etcd snapshot to host
  copy:
    src: "{{ etcd_snapshot }}"
    dest: /tmp/snapshot.db
    mode: "0640"
  when: etcd_snapshot is defined

- name: Stop etcd
  systemd_service:
    name: etcd
    state: stopped

- name: Remove etcd data-dir
  file:
    path: "{{ etcd_data_dir }}"
    state: absent

- name: Restore etcd snapshot  # noqa command-instead-of-shell
  shell: "{{ bin_dir }}/etcdctl snapshot restore /tmp/snapshot.db --name {{ etcd_member_name }} --initial-cluster {{ etcd_member_name }}={{ etcd_peer_url }} --initial-cluster-token k8s_etcd --initial-advertise-peer-urls {{ etcd_peer_url }} --data-dir {{ etcd_data_dir }}"
  environment:
    ETCDCTL_CERT: "{{ etcd_cert_dir }}/admin-{{ inventory_hostname }}.pem"
    ETCDCTL_KEY: "{{ etcd_cert_dir }}/admin-{{ inventory_hostname }}-key.pem"
    ETCDCTL_CACERT: "{{ etcd_cert_dir }}/ca.pem"
    ETCDCTL_ENDPOINTS: "{{ etcd_access_addresses }}"
    ETCDCTL_API: "3"

- name: Remove etcd snapshot
  file:
    path: /tmp/snapshot.db
    state: absent

- name: Change etcd data-dir owner
  file:
    path: "{{ etcd_data_dir }}"
    owner: etcd
    group: etcd
    recurse: true

- name: Reconfigure etcd
  replace:
    path: /etc/etcd.env
    regexp: "^(ETCD_INITIAL_CLUSTER=).*"
    replace: '\1{{ etcd_member_name }}={{ etcd_peer_url }}'

- name: Start etcd
  systemd_service:
    name: etcd
    state: started
