# 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 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: Calculate virtual host name when running scale out"
  ansible.builtin.set_fact:
    db_virtualhost_temp:  >-
                                       {%- set _host_name = hostvars[db_server_temp | first]['virtual_host'] -%}
                                       {%- if database_scale_out and not database_high_availability -%}
                                       {%-  set _host_name = sap_sid | lower ~ db_sid | lower ~ 'db' ~ db_instance_number ~ 'so' -%}
                                       {%- endif -%}
                                       {{- _host_name -}}

- name:                                "APP Install: Set BOM facts"
  ansible.builtin.set_fact:
    sap_inifile:                       "{{ bom_base_name }}-app-{{ sid_to_be_deployed.sid }}-{{ ansible_hostname }}.params"
    sap_inifile_template:              "app-inifile-param.j2"
    dir_params:                        "{{ tmp_directory }}/.{{ sid_to_be_deployed.sid | upper }}-params"
    db_lb_virtual_host_HANA:           "{% if database_high_availability %}{{ sid_to_be_deployed.sid | lower }}{{ db_sid | lower }}db{{ db_instance_number }}cl{% else %}{{ db_virtualhost_temp | default(hostvars[db_server_temp | first]['virtual_host'], true) }}{% endif %}"
    db_lb_virtual_host_AnyDB:          "{% if database_high_availability %}{{ sid_to_be_deployed.sid | lower }}{{ db_sid | lower }}db{{ db_instance_number }}cl{% else %}{{ db_server_temp }}{% endif %}"
    app_virtual_hostname:              "{{ virtual_host }}"

- name:                                "APP Install: Set BOM facts db host"
  ansible.builtin.set_fact:
    db_lb_virtual_host:                "{% if platform == 'HANA' %}{{ custom_db_virtual_hostname | default(db_lb_virtual_host_HANA, true) }}{% else %}{{ custom_db_virtual_hostname | default(db_lb_virtual_host_AnyDB, true) }}{% endif %}"

- name:                                "APP Install: -  Create directories"
  ansible.builtin.file:
    path:                              "{{ item.path }}"
    state:                             directory
    mode:                              '{{ item.mode }}'
  loop:
    - { mode: '0755', path: '{{ dir_params }}' }
    - { mode: '0775', path: '{{ tmp_directory }}/{{ sid_to_be_deployed.sid | upper }}' }
    - { mode: '0755', path: '/etc/sap_deployment_automation/{{ sap_sid | upper }}' }

- name:                                "APP Install: reset"
  ansible.builtin.file:
    path:                              "/etc/sap_deployment_automation/{{ sid_to_be_deployed.sid | upper }}/sap_deployment_app.txt"
    state:                             absent
  when:                                reinstall

- name:                                "APP Install: check if {{ sid_to_be_deployed.sid | upper }} is installed"
  ansible.builtin.stat:
    path:                              "/etc/sap_deployment_automation/{{ sid_to_be_deployed.sid | upper }}/sap_deployment_app.txt"
  register:                            app_installed

# Returns bom object
- name:                                "APP Install: Register BoM"
  ansible.builtin.include_role:
    name:                              roles-sap/3.3.1-bom-utility
    tasks_from:                        bom-register
  vars:
    bom_name:                          "{{ bom_base_name }}"
    task_prefix:                       "APP Install: "
    sa_enabled:                        true

- name:                                "APP Install: register variables"
  ansible.builtin.set_fact:
    app_bom_id:                        "{% if database_high_availability %}{{ bom.product_ids.app_ha | default(bom.product_ids.app) }}{% else %}{{ bom.product_ids.app }}{% endif %}"

- name:                                "APP Install: Check if the DB load balancer port is available and listening"
  ansible.builtin.wait_for:
    host:                              "{{ db_lb_virtual_host }}"
    port:                              "3{{ db_instance_number }}13"
    state:                             started
    timeout:                           30
    msg:                               'INSTALL:0026:APP Install failed, database is unreachable.'
  register:                            db_port_open
  failed_when:                         false
  when:
    - database_high_availability
    - platform == "HANA"

- name:                                "APP Install: DEBUG - DB Loadbalancer check"
  ansible.builtin.debug:
    msg:                               "{{ db_port_open.msg }}"
    verbosity:                         2
  when:
    - database_high_availability
    - platform == "HANA"
    - db_port_open.msg is defined

- name:                                "ErrorHandling"
  ansible.builtin.fail:
    msg:                               "INSTALL:0026:APP Install failed, database is unreachable."
  when:
    - database_high_availability
    - platform == "HANA"
    - db_port_open.msg is defined

- name:                                "APP Install: Check if the DB load balancer port is available and listening"
  ansible.builtin.wait_for:
    host:                              "{{ db_lb_virtual_host }}"
    port:                              "3{{ db_instance_number }}13"
    state:                             started
    timeout:                           30
    msg:                               'INSTALL:0026:APP Install failed, database is unreachable.'
  register:                            db_port_open
  failed_when:                         false
  when:
    - database_high_availability
    - platform == "HANA"

- name:                                "APP Install: DEBUG - DB Loadbalancer check"
  ansible.builtin.debug:
    msg:                               "{{ db_port_open.msg }}"
    verbosity:                         2
  when:
    - database_high_availability
    - platform == "HANA"
    - db_port_open.msg is defined

- name:                                "ErrorHandling"
  ansible.builtin.fail:
    msg:                               "INSTALL:0026:APP Install failed, database is unreachable."
  when:
    - database_high_availability
    - platform == "HANA"
    - db_port_open.msg is defined

- name:                               "APP Install: Set Schema Name"
  when:
    - platform == "HANA"
  ansible.builtin.include_role:
    name:                             "roles-db/4.0.4-hdb-schema"
    public:                           true

# *====================================4=======================================8
#   SAP APP: Install
# 2230669 - System Provisioning Using a Parameter Input File
#
- name:                                "APP Install"
  when:                                not app_installed.stat.exists
  block:
    - name:                            "APP Install: Set the SCS Server name"
      ansible.builtin.set_fact:
        scs_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/APPX{% else %}INSTALL/DISTRIBUTED/ABAP/APPS{% endif %}"

    - name:                            "APP Install: check media exists"
      ansible.builtin.stat:
        path:                          "{{ target_media_location }}/SWPM/sapinst"
      register:                        sapinst_found

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

    - name:                            "APP Install: Template processing - Create ini file {{ sap_inifile }} from {{ sap_inifile_template }}"
      ansible.builtin.template:
        src:                           "{{ sap_inifile_template }}"
        dest:                          "{{ dir_params }}/{{ sap_inifile }}"
        mode:                          0644
        force:                         true
      vars:
        sap_cd_package_hdbclient:      "{{ target_media_location }}/CD_HDBCLIENT/SAP_HANA_CLIENT"
        sap_cd_package_cd1:            "{{ target_media_location }}/CD_EXPORT"
        sap_ciInstanceNumber:          "{{ sid_to_be_deployed.ascs_inst_no }}"
        app_instance_number:           "{{ sid_to_be_deployed.app_inst_no }}"
        sap_ciDialogWPNumber:          12
        sap_ciBtcWPNumber:             8
        sap_installSAPHostAgent:       "false"
        sap_profile_dir:               /sapmnt/{{ sid_to_be_deployed.sid | upper }}/profile
        sap_scs_hostname:              "{{ custom_scs_virtual_hostname | default(scs_server, true) }}"
        sap_db_hostname:               "{{ custom_db_virtual_hostname | default(db_lb_virtual_host, true) }}"
        sap_ciVirtualHostname:         "{{ query('inventory_hostnames', '{{ sap_sid | upper }}_APP') | first }}"
        sap_appVirtualHostname:        "{{ app_virtual_hostname }}"
        param_directory:               "{{ dir_params }}"
        sap_sid:                       "{{ sid_to_be_deployed.sid }}"
        sidadm_uid:                    "{{ sid_to_be_deployed.sidadm_uid }}"
        virt_do_not_resolve_hostname:  "{{ custom_db_virtual_hostname | default(db_lb_virtual_host, true) }}"
        hana_schema:                   "{{ schema_name | default('') }}"


    - name:                            "App Install: install variables"
      ansible.builtin.debug:
        msg:
          - "INSTALLED:  {{ app_installed.stat.exists }}"
          - "INIFILE:    {{ sap_inifile }}"
          - "PRODUCT ID: {{ bom.product_ids.app }}"
          - "DBHOST:     {{ custom_db_virtual_hostname | default(db_virtual_hostname, true) }}"
          - "HOST:       {{ app_virtual_hostname }}"
          - "SID:        {{ sid_to_be_deployed.sid | upper }}"

    - name:                            "APP Install: HANA HSR - Update Profile"
      ansible.builtin.import_tasks:    ../../../roles-db/4.0.1-hdb-hsr/tasks/4.0.1.7-sap-profile-changes.yml
      when:
        - database_high_availability
        - platform == "HANA"

    - name:                            "APP Install: Create temp directory for sid"
      ansible.builtin.file:
        path:                          "{{ tmp_directory }}/{{ sid_to_be_deployed.sid | upper }}"
        state:                         directory
        mode:                          0755

    - name:                            "APP Install: Create Symlink"
      ansible.builtin.import_tasks:    ../../../roles-sap-os/2.10-sap-notes/tasks/2.10.3119751.yaml
      when:
        - ansible_os_family == 'RedHat'

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

    - name:                            "APP Install: Running sapinst"
      ansible.builtin.shell: |
                                       umask {{ custom_umask | default('022') }} ;
                                       ./sapinst SAPINST_INPUT_PARAMETERS_URL={{ dir_params }}/{{ sap_inifile }} \
                                                 SAPINST_EXECUTE_PRODUCT_ID={{ app_bom_id }}                     \
                                                 SAPINST_SKIP_DIALOGS=true                                       \
                                                 SAPINST_USE_HOSTNAME={{ app_virtual_hostname }}                 \
                                                 SAPINST_START_GUISERVER=false
      args:
        chdir:                         "{{ target_media_location }}/SWPM"
        creates:                       "/etc/sap_deployment_automation/{{ sid_to_be_deployed.sid | upper }}/sap_deployment_app.txt"
      environment:
        SAPSYSTEMNAME:                 "{{ sid_to_be_deployed.sid | upper }}"
        TMPDIR:                        "{{ tmp_directory }}/{{ sid_to_be_deployed.sid | upper }}"
      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.builtin.file:
        path:                          "{{ dir_params }}/{{ sap_inifile }}"
        state:                         absent

    - name:                            "APP Install: Find the installationSuccesfullyFinished.dat (SAPINST)"
      ansible.builtin.find:
        paths:                         "{{ tmp_directory }}/{{ sid_to_be_deployed.sid | upper }}/sapinst_instdir/{{ bom.product_ids.app.replace('.', '/').replace('/ABAP', '').split(':')[1] }}/{{ file_path }}"
        file_type:                     file
        patterns:                      'installationSuccesfullyFinished.dat'
        recurse:                       true
      register:                        app_installed_according_to_sapinst

    - name:                            "APP Install: flag"
      ansible.builtin.file:
        path:                          "/etc/sap_deployment_automation/{{ sid_to_be_deployed.sid | upper }}/sap_deployment_app.txt"
        state:                         touch
        mode:                          0755
      when:
        - app_installation.rc == 0
        - app_installed_according_to_sapinst is defined
        - app_installed_according_to_sapinst | length > 0

    - name:                            "APP Install: Get hdbuserstore path"
      become:                          true
      become_user:                     "root"
      ansible.builtin.find:
        paths:                         "/usr/sap/{{ sid_to_be_deployed.sid | upper }}/SYS/exe/uc/linuxx86_64/hdbclient/,/usr/sap/{{ sid_to_be_deployed.sid }}/hdbclient"
        file_type:                     file
        patterns:                      'hdbuserstore'
        recurse:                       true
      register:                        hdbuserstore_file
      vars:
        allow_world_readable_tmpfiles: true
      when:
        - database_high_availability
        - platform == 'HANA'

    - name:                            "APP Install: Set hdbuserstore path"
      ansible.builtin.set_fact:
        hdbuserstore_path:             "{{ hdbuserstore_file.files[0].path }}"
      when:
        - database_high_availability
        - platform == 'HANA'
        - hdbuserstore_file | length > 0
    - name:                            "APP Install: show hdbuserstore path"
      ansible.builtin.debug:
        var:                           hdbuserstore_path
      when:
        - database_high_availability
        - platform == 'HANA'

    - name:                            "APP Install: Set DB Virtual Host name"
      become:                          true
      become_user:                     "{{ sid_to_be_deployed.sid | lower }}adm"
      ansible.builtin.shell:           "{{ hdbuserstore_path }} -H {{ app_virtual_hostname }} SET DEFAULT {{ custom_db_virtual_hostname | default(db_lb_virtual_host, true) }}:3{{ db_instance_number }}13@{{ db_sid | upper }} {{ schema_name }} {{ main_password }}"
      environment:
        SAPSYSTEMNAME:                 "{{ sid_to_be_deployed.sid | upper }}"
        ssfs_connect:                  "1"
      register:                        hdbuserstore
      vars:
        allow_world_readable_tmpfiles: true
      when:
        - database_high_availability
        - platform == 'HANA'
        - app_installed_according_to_sapinst is defined
        - app_installed_according_to_sapinst | length > 0

    - name:                            "APP Install: Set DB Virtual Host name"
      become:                          true
      become_user:                     "{{ sid_to_be_deployed.sid | lower }}adm"
      ansible.builtin.shell:           "{{ hdbuserstore_path }}  SET DEFAULT {{ custom_db_virtual_hostname | default(db_lb_virtual_host, true) }}:3{{ db_instance_number }}13@{{ db_sid | upper }} {{ schema_name }} {{ main_password }}"
      environment:
        SAPSYSTEMNAME:                 "{{ sid_to_be_deployed.sid | upper }}"
        ssfs_connect:                  "1"
      register:                        hdbuserstore
      vars:
        allow_world_readable_tmpfiles: true
      when:
        - database_high_availability
        - platform == 'HANA'
        - app_installed_according_to_sapinst is defined
        - app_installed_according_to_sapinst | length > 0

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

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

    - name:                            "APP Install: - return value"
      ansible.builtin.set_fact:
        app_already_installed:         true

    - name:                            "APP Install: Get hdbuserstore path"
      become:                          true
      become_user:                     "root"
      ansible.builtin.find:
        paths:                         "/usr/sap/{{ sid_to_be_deployed.sid | upper }}/SYS/exe/uc/linuxx86_64/hdbclient/,/usr/sap/{{ sid_to_be_deployed.sid }}/hdbclient"
        file_type:                     file
        patterns:                      'hdbuserstore'
        recurse:                       true
      register:                        hdbuserstore_file
      vars:
        allow_world_readable_tmpfiles: true
      when:
        - database_high_availability
        - platform == 'HANA'

    - name:                            "APP Install: Set hdbuserstore path"
      ansible.builtin.set_fact:
        hdbuserstore_path:             "{{ hdbuserstore_file.files[0].path }}"
      when:
        - database_high_availability
        - platform == 'HANA'
        - hdbuserstore_file | length > 0

    - name:                            "APP Install: show hdbuserstore path"
      ansible.builtin.debug:
        var:                           hdbuserstore_path
      when:
        - database_high_availability
        - platform == 'HANA'

    - name:                            "APP Install: Set DB Virtual Host name ({{ custom_db_virtual_hostname | default(db_lb_virtual_host, true) }})"
      ansible.builtin.shell:           "{{ hdbuserstore_path }} -H {{ app_virtual_hostname }} SET DEFAULT {{ custom_db_virtual_hostname | default(db_lb_virtual_host, true) }}:3{{ db_instance_number }}13@{{ db_sid | upper }} {{ schema_name }} {{ main_password }}"
      environment:
        SAPSYSTEMNAME:                 "{{ sid_to_be_deployed.sid | upper }}"
        ssfs_connect:                  "1"
      register:                        hdbuserstore
      become:                          true
      become_user:                     "root"
      vars:
        allow_world_readable_tmpfiles: true
      when:
        - database_high_availability
        - platform == 'HANA'

    - name:                            "APP Install: Set DB Virtual Host name ({{ custom_db_virtual_hostname | default(db_lb_virtual_host, true) }})"
      ansible.builtin.shell:           "{{ hdbuserstore_path }} SET DEFAULT {{ custom_db_virtual_hostname | default(db_lb_virtual_host, true) }}:3{{ db_instance_number }}13@{{ db_sid | upper }} {{ schema_name }} {{ main_password }}"
      environment:
        SAPSYSTEMNAME:                 "{{ sid_to_be_deployed.sid | upper }}"
        ssfs_connect:                  "1"
      register:                        hdbuserstore
      become:                          true
      become_user:                     "root"
      vars:
        allow_world_readable_tmpfiles: true
      when:
        - database_high_availability
        - platform == 'HANA'

  when:
    - app_installed.stat.exists

# *====================================4=======================================8

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