#  Copyright 2022 Dell Inc. or its subsidiaries. All Rights Reserved.
#
#  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.
---

- name: Initial cobbler setup
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Initialize variables
      set_fact:
        multi_profile: false
        grub_option: 1

    - name: Run import command
      command: cobbler import --arch=x86_64 --path=/mnt/{{ provision_os }} --name="{{ provision_os }}"
      changed_when: false

    - name: Kickstart profile - centos
      copy:
        src: "/root/centos7.ks"
        dest: "/var/lib/cobbler/templates/sample.ks"
        mode: "{{ file_perm }}"
      tags: install
      when: provision_os == "centos"

    - name: Kickstart profile - rocky
      copy:
        src: "/root/rocky8.ks"
        dest: "/var/lib/cobbler/templates/sample.ks"
        mode: "{{ file_perm }}"
      tags: install
      when: provision_os == "rocky"

    - name: Kickstart profile - leap
      copy:
        src: "/root/leap15.xml"
        dest: "/var/lib/cobbler/templates/sample_autoyast.xml"
        mode: "{{ file_perm }}"
      tags: install
      when: provision_os == "leap"

    - name: Get the cobbler profile list
      command: cobbler profile list
      changed_when: false
      register: cobbler_profile_list
      failed_when: false

    - name: Check if cobbler_profile_list has more that one profile
      set_fact:
        multi_profile: true
      when:
        - cobbler_profile_list.stdout_lines| length > 1

    - name: Check if the provision os is in cobbler_profile_list
      set_fact:
        grub_option: "{{ index + 1 }}"
      when:
        - provision_os in item
        - multi_profile
      loop: "{{ cobbler_profile_list.stdout_lines | flatten(levels=1) }}"
      loop_control:
        index_var: index

    - name: Assign default grub option
      replace:
        path: "/var/lib/cobbler/grub_config/grub/grub.cfg"
        regexp: "^set default=.*"
        replace: "set default='{{ grub_option }}'"
      tags: install

    - name: Syncing of cobbler
      command: cobbler sync
      changed_when: false