# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

## This shares the primary's kubeconfig with the other's in the cluster

- name: Create folder for kubeconfig
  ansible.builtin.file:
    path: "{{ kubeconfig_shared_root }}"
    state: "directory"
    mode: '0777'
    group: sudo
    owner: root
  tags:
  - abm-post-install
  - abm-install
  - kubeconfig-share

# Copy the kubeconfig to all other in cluster
- name: Copy generated kubeconfig to other in cluster
  become_user: "{{ abm_install_user }}"
  command:
    cmd: "scp {{ abm_install_folder }}/bmctl-workspace/{{ cluster_name }}/{{ cluster_name }}-kubeconfig {{ abm_install_user }}@{{ machine }}:{{ kubeconfig_shared_location }}"
  loop: "{{ control_plane_ips }}"
  loop_control:
    loop_var: machine
  when:
    - primary_cluster_machine is defined
    - primary_cluster_machine == True
    - control_plane_ip != machine
  tags:
  - abm-post-install
  - abm-install
  - kubeconfig-share
  - kube-share

# On primary, setup symbolic link to the desired location
- name: Symbolic link for primary machines
  ansible.builtin.file:
    src: "{{ abm_install_folder }}/bmctl-workspace/{{ cluster_name }}/{{ cluster_name }}-kubeconfig"
    dest: "{{ kubeconfig_shared_location }}"
    state: link
    mode: '0666'
  when:
    - primary_cluster_machine is defined
    - primary_cluster_machine == true
  tags:
  - abm-post-install
  - abm-install
  - kubeconfig-share

- name: Set permissions to edit for all
  ansible.builtin.file:
    path: "{{ kubeconfig_shared_location }}"
    mode: '0666'
    follow: yes
  tags:
  - abm-post-install
  - abm-install
  - kubeconfig-share

- name: Test kubectl
  command:
    cmd: kubectl cluster-info
  environment:
    KUBECONFIG: "{{ kubeconfig_shared_location }}"
  tags:
  - abm-post-install
  - abm-install
  - kubeconfig-share
  - kubeconfig-verify
