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

# /*---------------------------------------------------------------------------8
# |                                                                            |
# |             SAP: Register BOM                                              |
# |         SAP APP: deploy APP Parameter file install template                |
# |         SAP APP: Install                                                   |
# |                                                                            |
# +------------------------------------4--------------------------------------*/

---
- name:                                "APP Install: Set BOM facts"
  ansible.builtin.set_fact:
    sap_inifile:                       "{{ bom_base_name }}-app-{{ sid_to_be_deployed.sid | lower }}-{{ ansible_hostname }}.params"
    sap_inifile_template:              "app-inifile-param.j2"
    dir_params:                        '{{ tmp_directory_windows }}\{{ sid_to_be_deployed.sid | lower }}-params'
    product_catalog:                   '{{ download_directory_windows }}\SWPM\product.catalog'

- name:                                "APP Install: Create run flag directory"
  ansible.windows.win_file:
    path:                              '{{ sap_deployment_automation }}\{{ sid_to_be_deployed.sid | upper }}'
    state:                             directory

#   0x) Create directory for parameter files
- name:                                "APP Install: Create params directory"
  ansible.windows.win_file:
    path:                              "{{ dir_params }}"
    state:                             directory

- name:                                "APP Install: Create temp directory for sid"
  ansible.windows.win_file:
    path:                              '{{ tmp_directory_windows }}\{{ sid_to_be_deployed.sid | upper }}'
    state:                             directory

#   1x) Create directories for sapinst_extraction if not existing.
- name:                                "APP Install: Create sapinst Extraction Directory"
  ansible.windows.win_file:
    path:                              '{{ download_directory_windows }}\sap_extract'
    state:                             directory
  vars:
    ansible_become:                    true
    ansible_become_method:             ansible.builtin.runas
    ansible_become_user:               '{{ sap_sid }}adm@{{ domain_name }}'
    ansible_become_password:           "{{ domain_user_password }}"

- name:                                "APP Install: Create log Directory"
  ansible.windows.win_file:
    path:                              '{{ log_dir_windows }}\sapinst_logs'
    state:                             directory

- name:                                "APP Install: reset"
  ansible.windows.win_file:
    path:                              '{{ sap_deployment_automation }}\{{ sid_to_be_deployed.sid | upper }}\sap_deployment_pas.txt'
    state:                             absent
  when:                                reinstall

- name:                                "APP Install: check if {{ sid_to_be_deployed.sid | upper }} is installed"
  ansible.windows.win_stat:
    path:                              '{{ sap_deployment_automation }}\{{ sid_to_be_deployed.sid | upper }}\sap_deployment_pas.txt'
  register:                            app_installed

- name:                                "APP Install: Set the SCS Server name list"
  ansible.builtin.set_fact:
    scs_server_temp:                   "{{ scs_server_temp | default([]) + [item] }}"
  with_items:
    - "{{ query('inventory_hostnames', '{{ sap_sid | upper }}_SCS') }}"
    - "{{ query('inventory_hostnames', '{{ sap_sid | upper }}_DB') }}"

- name:                                "APP Install: -  Set the DB Server name list"
  ansible.builtin.set_fact:
    db_server_temp:                    "{{ db_server_temp | default([]) + [item] }}"
  with_items:
    - "{{ query('inventory_hostnames', '{{ sap_sid | upper }}_DB') }}"

- name:                            "Backward Compatibility - Check required Database HA variables"
  ansible.builtin.set_fact:
    database_high_availability:    "{{ db_high_availability | default(false) }}"
  when:
    - db_high_availability is defined
    - database_high_availability is not defined

- name:                                "APP Install: Set the SCS Server name"
  ansible.builtin.set_fact:
    scs_server:                        "{{ hostvars[scs_server_temp | first]['virtual_host'] }}"
    scs_sapmnt_server:                 "{% if scs_high_availability %}{{ sid_to_be_deployed.sid | lower }}scs{{ scs_instance_number }}cl1{% else %}{{ hostvars[scs_server_temp | first]['virtual_host'] }}{% endif %}"
    db_virtual_hostname:               "{{ hostvars[db_server_temp | first]['virtual_host'] }}"
    file_path:                         "{% if scs_high_availability %}INSTALL/HA/ABAP/APP1{% else %}INSTALL/DISTRIBUTED/ABAP/APP1{% endif %}"
    db_lb_virtual_host:                "{% if database_high_availability %}{{ sid_to_be_deployed.sid | lower }}{{ db_sid | lower }}db{{ db_instance_number }}cl{% else %}{{ hostvars[db_server_temp | first]['virtual_host'] }}{% endif %}"

- name:                                "APP Install: Include 3.3.1-bom-utility role"
  ansible.builtin.include_role:
    name:                              roles-sap/windows/3.3.1-bom-utility
    tasks_from:                        bom-register
  vars:
    bom_name:                          "{{ bom_base_name }}"
    tier:                              "app"
    task_prefix:                       "APP Install: "
    sa_enabled:                        true

- name:                               "APP Install: Create ini file {{ sap_inifile }}"
  ansible.windows.win_template:
    src:                              "{{ sap_inifile_template }}"
    dest:                             '{{ dir_params }}\{{ sap_inifile }}'
    force:                            true
  vars:
    sap_cd_package_hdbclient:          '{{ download_directory_windows }}\CD_HDBCLIENT\SAP_HANA_CLIENT'
    sap_cd_package_cd1:                '{{ download_directory_windows }}\CD_EXPORT'
    sap_cd_package_cd2:
    sap_cd_package_cd3:
    sap_cd_package_cd4:
    sap_cd_package_cd5:
    sap_ciInstanceNumber:              "{{ instance_number }}"
    app_instance_number:
    sap_ciDialogWPNumber:              12
    sap_ciBtcWPNumber:                 8
    sap_installSAPHostAgent:           "false"
    sap_profile_dir:                   '\\{{ scs_sapmnt_server }}\sapmnt\{{ sid_to_be_deployed.sid | upper }}\SYS\profile'
    sap_scs_hostname:                  "{{ scs_sapmnt_server }}"
    sap_db_hostname:                   "{{ custom_db_virtual_hostname | default(db_virtual_hostname, true) }}"
    sap_ciVirtualHostname:
    sap_appVirtualHostname:            "{{ virtual_host }}"
    param_directory:                   "{{ dir_params }}"
    sap_sid:                           "{{ sid_to_be_deployed.sid }}"
    scs_instance_number:               "{{ sid_to_be_deployed.ascs_inst_no }}"
    sidadm_uid:                        "{{ sid_to_be_deployed.sidadm_uid }}"
    virt_do_not_resolve_hostname:      "{{ custom_db_virtual_hostname | default(db_lb_virtual_host, true) }}"

- name:                                "APP Install: register variables"
  ansible.builtin.set_fact:
    app_bom_id:                        "{{ bom.product_ids.app }}"

- name:                                "APP Install: install variables"
  ansible.builtin.debug:
    msg:
      - "INSTALLED:  {{ app_installed.stat.exists }}"
      - "INIFILE:    {{ sap_inifile }}"
      - "PRODUCT ID: {{ app_bom_id }}"
      - "INSTANCE:   {{ instance_number }}"
      - "DBHOST:     {{ custom_db_virtual_hostname | default(db_virtual_hostname, true) }}"
      - "HOST:       {{ virtual_host }}"
      - "SID:        {{ sid_to_be_deployed.sid | upper }}"

- name:                                "APP Install: - status"
  block:

    - name:                            "APP Install: - status"
      ansible.builtin.debug:
        msg:                           "APP Install: is already performed ({{ sid_to_be_deployed.sid | upper }})"

    - name:                            "APP Install: - return value"
      ansible.builtin.set_fact:
        pas_already_installed:         true
      when:
        - app_installed.stat.exists

    # *====================================4=======================================8
    # |  SAP APP: Install                                                          |
    # | 2230669 - System Provisioning Using a Parameter Input File                 |
    # |                                                                            |
    # *====================================4=======================================8

    - name:                            "APP Install: progress"
      ansible.builtin.debug:
        msg:                           "Starting APP installation ({{ sid_to_be_deployed.sid | upper }})"

    - name:                            "APP Install: sapinst Extraction"
      ansible.windows.win_shell: |
                                       {{ download_directory_windows }}\SWPM\sapinst.exe -extract
      args:
        chdir:                         '{{ download_directory_windows }}\sap_extract'
        creates:                       '{{ download_directory_windows }}\sap_extract\sapinst.exe'
      vars:
        ansible_become:                true
        ansible_become_method:         ansible.builtin.runas
        ansible_become_user:           '{{ sap_sid }}adm@{{ domain_name }}'
        ansible_become_password:       "{{ domain_user_password }}"
      register:                        scs_extraction
      failed_when:                     scs_extraction.rc > 0

    - name:                            "APP Install"
      ansible.windows.win_shell: |
                                       {{ download_directory_windows }}\sap_extract\sapinst.exe SAPINST_INPUT_PARAMETERS_URL={{ dir_params }}\{{ sap_inifile }}  `
                                                                                                SAPINST_EXECUTE_PRODUCT_ID={{ app_bom_id }}                      `
                                                                                                SAPINST_SKIP_DIALOGS=true                                        `
                                                                                                SAPINST_CONTROL_URL={{ product_catalog }}                        `
                                                                                                SAPINST_START_GUI=false                                          `
                                                                                                SAPINST_START_GUISERVER=false
      args:
        chdir:                         '{{ log_dir_windows }}\sapinst_logs'
        creates:                       '{{ sap_deployment_automation }}\{{ sid_to_be_deployed.sid | upper }}\sap_deployment_pas.txt'
      vars:
        ansible_become:                true
        ansible_become_method:         ansible.builtin.runas
        ansible_become_user:           '{{ sap_sid }}adm@{{ domain_name }}'
        ansible_become_password:       "{{ domain_user_password }}"
      register:                        app_installation
      failed_when:                     app_installation.rc > 0

    - name:                            "APP Install: Installation results"
      ansible.builtin.debug:
        var:                           app_installation
      when:                            app_installation.rc > 0

    - name:                            "APP Install: Installation results"
      ansible.builtin.debug:
        msg:                           "APP Installation succeeded"
      when:                            app_installation.rc == 0

    - name:                            "APP Install: Cleanup ini file {{ ansible_hostname }}"
      ansible.windows.win_file:
        path:                          '{{ dir_params }}\{{ sap_inifile }}'
        state:                         absent

    - name:                            "APP Install: Find the installationSuccesfullyFinished.dat (SAPINST)"
      ansible.windows.win_find:
        paths:                         '{{ log_dir_windows }}\sapinst_logs'
        file_type:                     file
        patterns:                      'installationSuccesfullyFinished.dat'
        recurse:                       true
      register:                        app_installed_according_to_sapinst

    - name:                            "APP Install: flag"
      ansible.windows.win_file:
        path:                          '{{ sap_deployment_automation }}\{{ sid_to_be_deployed.sid | upper }}\sap_deployment_pas.txt'
        state:                         touch
      when:
        - app_installation.rc == 0
        - app_installed_according_to_sapinst is defined
        - app_installed_according_to_sapinst.matched > 0

  when:
    - not app_installed.stat.exists

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