# Copyright 2021 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: Check if idrac_vault_key exists
  stat:
    path: "{{ idrac_tools_vaultname }}"
  register: idrac_vault_key_result

- name: Create ansible vault key if it does not exist
  set_fact:
    idrac_vault_key: "{{ lookup('password', '/dev/null chars=ascii_letters') }}"
  when: not idrac_vault_key_result.stat.exists

- name: Save vault key
  copy:
    dest: "{{ idrac_tools_vaultname }}"
    content: |
      {{ idrac_vault_key }}
    owner: root
    force: yes
    mode: "{{ vault_file_perm }}"
  when: not idrac_vault_key_result.stat.exists

- name: Check if idrac_tools_vars.yml file is encrypted
  command: cat {{ idrac_tools_vars_filename }}
  changed_when: false
  register: idrac_tools_content
  no_log: True

- name: Encrpyt idrac_tools_vars.yml
  command: >-
    ansible-vault encrypt {{ idrac_tools_vars_filename }} --vault-password-file {{ idrac_tools_vaultname }}
  changed_when: true
  when: "'$ANSIBLE_VAULT;' not in idrac_tools_content.stdout"

- name: Update idrac_tools_vars.yml permission
  file:
    path: "{{ idrac_tools_vars_filename }}"
    mode: "{{ vault_file_perm }}"