- name: Install requirements
  become: true
  ansible.builtin.package:
    pkg: "{{ item }}"
    state: present
  loop:
    - python3-pip
    - python3-virtualenv
    - snapd
    - jq
  tags: always

- name: Read current remote $HOME
  ansible.builtin.shell: "echo $HOME"
  register: remote_home_dir
  changed_when: false
  check_mode: false
  tags: always

- name: Set working folders
  ansible.builtin.set_fact:
    k8s_etc: "{{ remote_home_dir.stdout }}/.kube"
    k8s_kubeconfig: "{{ remote_home_dir.stdout }}/.kube/config"
    k8s_venv: "{{ remote_home_dir.stdout }}/.venv"
  tags: always

- name: Create required folders
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    mode: "0750"
  loop:
    - "{{ k8s_etc }}"
    - "{{ k8s_venv }}"
  tags: always

- name: Install required PIP packages
  ansible.builtin.pip:
    name: "{{ item }}"
    state: present
    virtualenv: "{{ k8s_venv }}"
    virtualenv_site_packages: true
  loop:
    - kubernetes
    - yq
  tags: always

- name: Install Microk8s
  ansible.builtin.include_tasks: microk8s/install.yml
  tags:
    - k8s::install

- name: Download kubectl
  become: true
  ansible.builtin.get_url:
    url: "https://dl.k8s.io/release/v{{ microk8s_kubectl_version }}/bin/linux/amd64/kubectl"
    dest: "/usr/local/bin/kubectl"
    mode: "0755"
    owner: "root"
  tags:
    - k8s::install
    - k8s::kubectl

- name: Setup LoadBalancer
  ansible.builtin.include_tasks: loadbalancer.yml
  tags:
    - k8s::loadbalancer

- name: Setup CertManager
  ansible.builtin.include_tasks: certmanager.yml
  tags:
    - k8s::certmanager

- name: Setup IAC access
  ansible.builtin.include_tasks: iac.yml
  tags:
    - k8s::iac

- name: "Setup local user access to k8s - {{ item.username }}"
  ansible.builtin.include_tasks: "setupenv/main.yml"
  loop: "{{ microk8s_users }}"
  when: microk8s_users is defined
  tags:
    - k8s::users
