# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

# /*---------------------------------------------------------------------------8
# |                                                                            |
# |     Storage account helpers                                                |
# |     Read the deployer key vault name fro the workload zone keyvault        |
# |     Read the storage account details                                       |
# |                                                                            |
# +------------------------------------4--------------------------------------*/
---
- name:                                "0.4 Installation Media: - Retrieve Deployer Keyvault details"
  block:

    - name:                            Check required variables are present and not empty
      ansible.builtin.assert:
        that:
          - "kv_name is defined"                    # Has the variable been defined
          - "kv_name | type_debug != 'NoneType'"    # and given a value
          - "kv_name | string | length != 0 "       # Detect null values
        fail_msg:                      "Please define the kv_name parameter"

    - name:                            "Parameters to be used..."
      ansible.builtin.debug:
        msg:                                  # Best method for formatting output with Azure Devops Logs
                                       - "kv_name:                         {{ kv_name }}"
                                       - "deployer_kv_name_secret:    {{ deployer_kv_name_secret }}"
        verbosity:                     2

    - name:                            "0.4 Installation Media: - Get Deployer key vault name workload zone key vault"
      ansible.builtin.command: >-
                                       az keyvault secret show
                                         --vault-name {{ kv_name }}
                                         --name {{ deployer_kv_name_secret }}
                                         --query value
                                         --output tsv
      changed_when:                    false
      register:                        deployer_kv_name_secret_result
      when:                            bom_processing is not defined

    - name:                            "0.4 Installation Media: - Save Deployer key vault name"
      ansible.builtin.set_fact:
        deployer_kv_name:              "{{ deployer_kv_name_secret_result.stdout }}"
        cacheable:                     true

  when: deployer_kv_name is not defined

- name:                                   "Parameter review..."
  ansible.builtin.debug:
    msg:                                  # Best method for formatting output with Azure Devops Logs
                                          - "kv_name:                         {{ kv_name }}"
                                          - "deployer_kv_name_secret:         {{ deployer_kv_name_secret }}"
                                          - "deployer_kv_name:                {{ deployer_kv_name }}"
    verbosity:                            2

- name:                                "0.4 Installation Media: - Get Control Plane Subscription"
  ansible.builtin.set_fact:
    control_plane_subscription_id:     "{{ lookup('ansible.builtin.env', 'control_plane_subscription') | default('') }}"

- name:                                "0.4 Installation Media: - Extract SAP Binaries Storage Account SAS (temp)"
  ansible.builtin.set_fact:
    subscription_parameter:            "{% if control_plane_subscription_id | length > 0 %}--subscription {{ control_plane_subscription_id }}{% else %}{% endif %}"

- name:                                "0.4 Installation Media: - Extract SAP Binaries Storage Account secrets"
  block:
    - name:                            "0.4 Installation Media: - Extract SAP Binaries Storage Account information"
      ansible.builtin.command: >-
                                       az keyvault secret show
                                         --vault-name {{ deployer_kv_name }}
                                         --name {{ sapbits_location_secret }}
                                         --query value
                                         --output tsv
      changed_when:                    false
      register:                        sapbits_location_base_path_secret
      no_log:                          false

    - name:                            "0.4 Installation Media: - Save SAP Binaries Storage Account information"
      ansible.builtin.set_fact:
        sapbits_location_base_path:    "{{ sapbits_location_base_path_secret.stdout }}"
        cacheable:                     true
  when:                                sapbits_location_base_path is not defined

- name:                                "0.4 Installation Media: - Save SAP Binaries Storage Account information"
  ansible.builtin.set_fact:
    account_name:                      "{{ sapbits_location_base_path.rpartition('//')[2].split('.')[0] }}"
    container_name:                    "{{ sapbits_location_base_path.rpartition('//')[2].split('/')[1] }}"
  when:                                sapbits_location_base_path is defined

- name:                                "0.4 Installation Media: - Extract Shared Key Access token flag"
  ansible.builtin.set_fact:
    allowSharedKeyAccess:             false

- name:                                "0.4 Installation Media: - Check Binaries Storage Account for Shared Key Access with Control Plane Subscription"
  when:
    - not is_executed_by_acss
  ansible.builtin.command: >-
                                       az storage account show          \
                                         --name {{ account_name }}      \
                                         --query allowSharedKeyAccess   \
                                         {{ subscription_parameter }}   \
                                         --out tsv
  changed_when:                        false
  register:                            az_allowSharedKeyAccess

- name:                                "0.4 Installation Media: - Extract Shared Key Access token flag"
  ansible.builtin.set_fact:
    allowSharedKeyAccess:             "{{ az_allowSharedKeyAccess.stdout | bool }}"
  when: az_allowSharedKeyAccess.stdout is defined and az_allowSharedKeyAccess.stdout | length > 0

- name:                                "Parameter review..."
  ansible.builtin.debug:
    msg:                               # Best method for formatting output with Azure Devops Logs
                                       - "Storage account_name:            {{ account_name }}"
                                       - "allowSharedKeyAccess:            {{ allowSharedKeyAccess }}"

- name:                                "0.4 Installation Media: - Retrieve Access Key secret"
  when:
   - allowSharedKeyAccess
   - sapbits_access_key is not defined
  block:
    - name:                            "0.4 Installation Media: - Check if Access Key secret exists"
      ansible.builtin.command: >-
        az keyvault secret list
          --vault-name {{ deployer_kv_name }} --query "[?name=='sapbits-access-key'].name | [0]" --output tsv
      changed_when:                    false
      register:                        keyvault_secrets

    - name:                            "0.4 Installation Media: - Retrieve Access Key details"
      ansible.builtin.command: >-
        az keyvault secret show
          --vault-name {{ deployer_kv_name }}
          --name "sapbits-access-key"
          --query value
          --output tsv
      changed_when:                    false
      no_log:                          true
      register:                        keyvault_secret_show_accesskey
      when:                            keyvault_secrets.stdout | length > 0

    - name:                            "0.4 Installation Media: - Extract Access Key details"
      ansible.builtin.set_fact:
        sapbits_access_key:            "{{ keyvault_secret_show_accesskey.stdout }}"
        cacheable:                     true
      when:
        - keyvault_secrets.stdout | length > 0
        - keyvault_secret_show_accesskey is defined

- name:                                "0.4 Installation Media: - Retrieve SAS token secret details"
  when:
    - sapbits_access_key is not defined
    - sapbits_sas_token is not defined or (sapbits_sas_token | string | length == 0)
    - allowSharedKeyAccess
  block:
    - name:                            "0.4 Installation Media: - Check if SAS token secret exists"
      ansible.builtin.command: >-
        az keyvault secret list
            --vault-name {{ deployer_kv_name }}
            --query "[?name =='sapbits-sas-token'].name | [0]"
            --output tsv
      changed_when:                    false
      register:                        keyvault_secrets

    - name:                            "0.4 Installation Media: - Retrieve SAS token details"
      ansible.builtin.command: >-
        az keyvault secret show
          --vault-name {{ deployer_kv_name }}
          --name "sapbits-sas-token"
          --query value
          --output tsv
      changed_when:                    false
      no_log:                          true
      register:                        keyvault_secret_show_sas_token
      when:                            keyvault_secrets.stdout | length > 0

    - name:                            "0.4 Installation Media: - Extract SAS token"
      ansible.builtin.set_fact:
        sapbits_sas_token:             "{{ keyvault_secret_show_sas_token.stdout }}"
        cacheable:                     true
      no_log:                          true
      when: keyvault_secret_show_sas_token is defined


- name:                                 "0.4 Installation Media: - Create SAP Binaries Storage Account SAS token"
  when:
    - sapbits_sas_token is not defined or (sapbits_sas_token | string | length == 0)
    - sapbits_access_key is defined
    - allowSharedKeyAccess
  block:

    - name:                             "0.4 Installation Media: - SAS token"
      ansible.builtin.debug:
        msg:                            "Creating the storage account SAS token"

    - name:                             "0.4 Installation Media: - Set Expiry"
      ansible.builtin.command:          "date +'%Y-%m-%d' -d '+3 days'"
      register:                         expiry

    - name:                            "0.4 Installation Media: - Create SAP Binaries Storage Account SAS in Control Plane subscription"
      ansible.builtin.command: >-
                                       az storage account generate-sas \
                                         --account-name {{ account_name }} \
                                         --expiry {{ expiry.stdout }} \
                                         --permissions crwl \
                                         --services b \
                                         --resource-types sco \
                                         --account-key {{ sapbits_access_key }} \
                                         {{ subscription_parameter }}   \
                                         --out tsv
      changed_when:                    false
      register:                        az_sapbits_sas_token

    - name:                            "0.4 Installation Media: - Debug storage account details (sas)"
      ansible.builtin.debug:
        var:                           az_sapbits_sas_token
        verbosity:                     4

    - name:                            "0.4 Installation Media: - Extract SAP Binaries Storage Account SAS (temp)"
      ansible.builtin.set_fact:
        sapbits_sas_token:             "{{ az_sapbits_sas_token.stdout }}"

- name:                                 "0.4 Installation Media: - Create User delegation SAP Binaries Storage Account SAS token"
  when:
    - sapbits_sas_token is not defined or (sapbits_sas_token | string | length == 0)
  block:

    - name:                             "0.4 Installation Media: - SAS token"
      ansible.builtin.debug:
        msg:                            "Creating the storage account SAS token"

    - name:                             "0.4 Installation Media: - Set Expiry"
      ansible.builtin.command:          "date +'%Y-%m-%d' -d '+3 days'"
      register:                         expiry

    - name:                            "0.4 Installation Media: - Create User delegation SAP Binaries Storage Account SAS in Control Plane subscription"
      ansible.builtin.command: >-
                                       az storage container generate-sas \
                                         --account-name {{ account_name }} \
                                         --name {{ container_name }} \
                                         --expiry {{ expiry.stdout }} \
                                         --permissions lr \
                                         --auth-mode login \
                                         --as-user  \
                                         {{ subscription_parameter }}   \
                                         --out tsv
      changed_when:                    false
      register:                        az_sapbits_sas_token

    - name:                            "0.4 Installation Media: - Debug storage account details (sas)"
      ansible.builtin.debug:
        var:                           az_sapbits_sas_token
        verbosity:                     4

    - name:                            "0.4 Installation Media: - Extract SAP Binaries Storage Account SAS (temp)"
      ansible.builtin.set_fact:
        sapbits_sas_token:             "{{ az_sapbits_sas_token.stdout }}"


- name:                                "0.0 Validations - Check required variables are present and not empty"
  ansible.builtin.assert:
    that:
      - sapbits_sas_token is defined                    # Has the variable been defined
      - sapbits_sas_token | trim | length > 1           # Does the variable have a value
    fail_msg: >-
      "The variable 'sapbits_sas_token' is not defined or is empty. Please provide it in the deployer key vault, sap-parameters file or pass it in as a parameter."

- name:                                 "0.4 Installation Media: - Debug storage account details"
  ansible.builtin.debug:
    msg:
      - "KEYVAULT:     {{ deployer_kv_name }}"
      - "URL     :     {{ sapbits_location_base_path }}"

- name:                                "0.4 Installation Media: - Debug storage account details (sas)"
  when:                                sapbits_sas_token is defined
  ansible.builtin.debug:
    msg:
      - "SAS     :     {{ sapbits_sas_token }}"
    verbosity:                         4

...
# /*---------------------------------------------------------------------------8
# |                                   END                                     |
# +------------------------------------4--------------------------------------*/
