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

# /*---------------------------------------------------------------------------8
# |                                                                            |
# |                Perform the SAP DB Instance installation                    |
# |                  SAP: Register BOM                                         |
# |                  create .params directory                                  |
# |                  deploy db install template                                |
# |                  deploy hdblcm password file                               |
# |                                                                            |
# +------------------------------------4--------------------------------------*/

---

# +------------------------------------4--------------------------------------*/
- name:                                "SAP HANA: Set BOM facts"
  ansible.builtin.set_fact:
    sap_inifile:                       "hdbserver_{{ virtual_host }}_{{ sap_sid }}_install.rsp"
    dir_params:                        "{{ tmp_directory }}/.params"

#   0x) Create hidden directory for parameter files
- name:                                "SAP HANA: Create directories"
  ansible.builtin.file:
    path:                              "{{ item.path }}"
    state:                             directory
    mode:                              '{{ item.mode }}'
  loop:
    - { mode: '0755', path: '{{ dir_params }}' }
    - { mode: '0755', path: '{{ tmp_directory }}/{{ db_sid | upper }}' }
    - { mode: '0755', path: '/etc/sap_deployment_automation/{{ db_sid | upper }}' }

- name:                                "SAP HANA: Install reset"
  ansible.builtin.file:
    path:                              "/etc/sap_deployment_automation/{{ db_sid | upper }}/sap_deployment_hdb.txt"
    state:                             absent
  when: reinstall

- name:                                "SAP HANA: check if installed"
  ansible.builtin.stat:
    path:                              "/etc/sap_deployment_automation/{{ db_sid | upper }}/sap_deployment_hdb.txt"
  register:                            hana_installed

- name:                                "SAP HANA: check media exists"
  ansible.builtin.stat:
    path:                              "{{ target_media_location }}/CD_HDBSERVER/SAP_HANA_DATABASE/hdblcm"
  register:                            hdblcm_found

- name:                                "ErrorHandling"
  ansible.builtin.fail:
    msg:                               "INSTALL:0001:Unable to find hdblcm, please check that the installation media is mounted"
  when: not hdblcm_found.stat.exists

- name:                                "SAP HANA: check sp version from manifest"
  ansible.builtin.shell: |
                                       set -o pipefail
                                       grep sp-number manifest | cut -d ":" -f 2 | tr -d [:space:]
  args:
    chdir:                             "{{ target_media_location }}/CD_HDBSERVER/SAP_HANA_DATABASE/server"
  register:                            manifest_hana_sp

- name:                                "SAP HANA: Show sps leve"
  ansible.builtin.debug:
    msg:                               "HANA SP Level: {{ manifest_hana_sp.stdout }}"

- name:                                "SAP HANA: Set fact when sps is 08 or higher"
  ansible.builtin.set_fact:
    hana_sp08_or_higher:               "{{ manifest_hana_sp.stdout is version('080', '>=') }}"

# all | client | es | ets | lcapps | server | smartda | streaming | rdsync | xs | studio | afl | sca | sop | eml | rme | rtl | trp
- name:                                "SAP HANA: Set HANA components"
  ansible.builtin.set_fact:
    hana_components:                   "server, lcapps, afl, vch2021"
  when:
    - hana_sp08_or_higher
    - hana_components == 'all'

- name:                                "SAP HANA: Show HANA components"
  ansible.builtin.debug:
    msg:                               "HANA Components: {{ hana_components }}"

- name:                                "HANA Install"
  block:

    - name:                            "SAP HANA: remove install response file if exists"
      ansible.builtin.file:
        path:                          "{{ dir_params }}/{{ sap_inifile }}"
        state:                         absent

    - name:                            "SAP HANA Template processing: Create ini file {{ sap_inifile }} from {{ HANA_2_00_install.rsp }}"
      ansible.builtin.template:
        src:                           "HANA_2_00_install.rsp"
        dest:                          "{{ dir_params }}/{{ sap_inifile }}"
        mode:                          0644
        force:                         true
  # Template parameter mapping
      vars:
        _rsp_component_root:           "../COMPONENTS"
        _rsp_components:               "{{ hana_components }}"
        _rsp_sapmnt:                   "/hana/shared"                              # Default Value
        _rsp_hostname:                 "{{ virtual_host }}"
        _rsp_sid:                      "{{ db_sid | upper }}"
        _rsp_number:                   "{{ db_instance_number }}"
        _rsp_system_usage:             "custom"
        pwd_hdb_system:                "{{ hana_system_user_password | default(main_password) }}"
        pwd_os_sidadm:                 "{{ hana_os_sidadm_password | default(main_password) }}"
        pwd_os_sapadm:                 "{{ hana_os_sapadm_password | default(main_password) }}"

        # use_master_password:           "{{ hana_use_master_password }}"
        # password_copy:                 "{{ main_password if hana_use_master_password == 'n' else '' }}"

    - name:                            "SAP HANA: Progress"
      ansible.builtin.debug:
        msg:                           "Start HANA Installation"

    - name:                            "SAP HANA: installation"
      block:
        - name:                        "SAP HANA: Execute hdblcm on {{ virtual_host }}"
          ansible.builtin.shell: |
                                       umask {{ custom_umask | default('022') }} ;
                                       chmod 755 /usr/sap;
                                       ./hdblcm --batch --action=install --hostname {{ virtual_host }} --configfile='{{ dir_params }}/{{ sap_inifile }}'
          args:
            chdir:                     "{{ target_media_location }}/CD_HDBSERVER/SAP_HANA_DATABASE"
            creates:                   "/etc/sap_deployment_automation/{{ db_sid | upper }}/sap_deployment_hdb.txt"
          environment:
            TMPDIR:                    "{{ tmp_directory }}/{{ db_sid | upper }}"
          register:                    hana_installation
          failed_when:                 hana_installation.rc > 0
      rescue:
        - name:                         "Fail if HANA installation failed with rc > 1"
          ansible.builtin.fail:
            msg:                        "INSTALL:0022:Execute hdblcm failed."
          when:                         hana_installation.rc > 1

        - name:                        "SAP HANA: Progress"
          ansible.builtin.debug:
            msg:                       "Restarting the HANA Installation"
          when:                        hana_installation.rc == 1


        - name:                        "SAP HANA: Re-execute hdblcm on {{ virtual_host }} and rescue"
          block:
            - name:                      "SAP HANA: Re-execute hdblcm on {{ virtual_host }}"
              ansible.builtin.shell: |
                                          umask {{ custom_umask | default('022') }} ;
                                          chmod 755 /usr/sap;
                                          ./hdblcm --batch --action=install --hostname {{ virtual_host }} --configfile='{{ dir_params }}/{{ sap_inifile }}'
              args:
                chdir:                     "{{ target_media_location }}/CD_HDBSERVER/SAP_HANA_DATABASE"
                creates:                   "/etc/sap_deployment_automation/{{ db_sid | upper }}/sap_deployment_hdb.txt"
              environment:
                TMPDIR:                    "{{ tmp_directory }}/{{ db_sid | upper }}"
              register:                    hana_installation
              failed_when:                 hana_installation.rc > 0
              when:                        hana_installation.rc == 1
          rescue:
            - name:                      "Fail if HANA installation failed while importing the delivery unit AHCO_INA_SERVICE"
              ansible.builtin.fail:
                msg:                       "INSTALL:0026:Execute hdblcm failed at delivery unit AHCO_INA_SERVICE."
              when:                        hana_installation.stderr is search(".*Import of delivery units failed.*Cannot import delivery unit.*AHCO_INA_SERVICE.tgz.*")

            - name:                        "Fail if HANA installation failed on second attempt."
              ansible.builtin.fail:
                msg:                       "INSTALL:0022:Execute hdblcm failed."

    - name:                            "SAP HANA: Installation results"
      ansible.builtin.debug:
        msg:
          - "HANA Installation failed"
          - "HDBLCM output: {{ hana_installation }}"
      when:
        - hana_installation.rc is defined
        - hana_installation.rc > 0

    - name:                            "Errorhandling: SAP HANA"
      ansible.builtin.debug:
        msg:                           "INSTALL:{{ hana_installation }}"
      when:
        - hana_installation.rc is defined
        - hana_installation.rc > 0

    - name:                            "SAP HANA: Successful installation"
      block:

        - name:                        "SAP HANA: Installation results"
          ansible.builtin.debug:
            msg:                       "HANA Installation succeeded"

        - name:                        "SAP HANA: HANA Install: flag"
          ansible.builtin.file:
            path:                      "/etc/sap_deployment_automation/{{ db_sid | upper }}/sap_deployment_hdb.txt"
            state:                     touch
            mode:                      0755

        - name:                        "SAP HANA: Create backup folder"
          ansible.builtin.file:
            path:                      "{{ hana_backup_path }}"
            state:                     directory
            group:                     sapsys
            owner:                     "{{ db_sid | lower }}adm"
            mode:                      0755

        - name:                        "Retrieve Subscription ID and Resource Group Name"
          ansible.builtin.uri:
            url:                       http://169.254.169.254/metadata/instance?api-version=2021-02-01
            use_proxy:                 false
            headers:
              Metadata:                true
          register: azure_metadata

        - name:                        "Extract details"
          ansible.builtin.set_fact:
            subscription_id:           "{{ azure_metadata.json.compute.subscriptionId }}"
            resource_group_name:       "{{ azure_metadata.json.compute.resourceGroupName }}"

        - name:                        "Show the subscription and resource group"
          ansible.builtin.debug:
            msg:
              - "Subscription ID: {{ subscription_id }}"
              - "Resource Group Name: {{ resource_group_name }}"

        - name:                        "Include deploy/ansible/roles-misc/0.6-ARM-Deployment"
          ansible.builtin.include_role:
            name:                      roles-misc/0.6-ARM-Deployment
          vars:
            subscriptionId:           "{{ subscription_id }}"
            resourceGroupName:       "{{ resource_group_name }}"

        - name:                        "SAP HANA: ARM Deployment flag"
          ansible.builtin.file:
            path:                      "/etc/sap_deployment_automation/{{ db_sid | upper }}/sap_deployment_hdb_arm.txt"
            state:                     touch
            mode:                      0755

        # - name:                        "SAP HANA: remove install response file"
        #   ansible.builtin.file:
        #     path:                      "{{ dir_params }}/{{ sap_inifile }}"
        #     state:                     absent


      when:
        - hana_installation.rc is defined
        - hana_installation.rc < 1

  when:
    - not hana_installed.stat.exists

- name:                                "HANA Install status"
  block:

    - name:                            "HANA Install status"
      ansible.builtin.debug:
        msg:                           "HANA is already installed"

    - name:                            "HANA: - return value"
      ansible.builtin.set_fact:
        hana_already_installed:         true

    - name:                            "SAP HANA: Create backup folder"
      ansible.builtin.file:
        path:                          "{{ hana_backup_path }}"
        state:                         directory
        group:                         sapsys
        owner:                         "{{ db_sid | lower }}adm"
        mode:                          0755

    - name:                            "SAP HANA: check if ARM Deployment done"
      ansible.builtin.stat:
        path:                          "/etc/sap_deployment_automation/{{ db_sid | upper }}/sap_deployment_hdb_arm.txt"
      register:                        hana_arm_deployment_done

    - name:                            "SAP HANA: Successful installation"
      block:
        - name:                        "Retrieve Subscription ID and Resource Group Name"
          ansible.builtin.uri:
            url:                       http://169.254.169.254/metadata/instance?api-version=2021-02-01
            use_proxy:                 false
            headers:
              Metadata:                true
          register: azure_metadata

        - name:                        "Extract details"
          ansible.builtin.set_fact:
            subscription_id_tmp:       "{{ azure_metadata.json.compute.subscriptionId }}"
            resource_group_name_tmp:   "{{ azure_metadata.json.compute.resourceGroupName }}"

        - name:                        "Show the subscription and resource group"
          ansible.builtin.debug:
            msg:
              - "Subscription ID: {{ subscription_id_tmp }}"
              - "Resource Group Name: {{ resource_group_name_tmp }}"

        - name:                        "Include deploy/ansible/roles-misc/0.6-ARM-Deployment"
          ansible.builtin.include_role:
            name:                      roles-misc/0.6-ARM-Deployment
          vars:
            subscription_id:           "{{ subscription_id_tmp }}"
            resource_group_name:       "{{ resource_group_name_tmp }}"

        - name:                        "SAP HANA: ARM Deployment flag"
          ansible.builtin.file:
            path:                      "/etc/sap_deployment_automation/{{ db_sid | upper }}/sap_deployment_hdb_arm.txt"
            state:                     touch
            mode:                      0755
      when:
        - not hana_arm_deployment_done.stat.exists

  when:
    - hana_installed.stat.exists

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