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

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

---

- name:                                "SCS Install"
  ansible.builtin.debug:
    msg:
      - "SID:        {{ sid_to_be_deployed.sid | upper }}"

- name:                                Get 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:                                "SCS Install: Set the SCS Server name"
  ansible.builtin.set_fact:
    scs_server: "{{ hostvars[scs_server_temp | first]['virtual_host'] }}"

- name:                                "SCS Install: Set BOM facts"
  ansible.builtin.set_fact:
    sap_inifile:                       "{{ bom_base_name }}-scs-{{ sid_to_be_deployed.sid | lower }}-{{ ansible_hostname }}.params"
    sap_inifile_template:              "scs-inifile-param.j2"
    dir_params:                        "{{ tmp_directory }}/.{{ sid_to_be_deployed.sid | lower }}-params"

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

# ToDo: Validate this works
# - name:                                "SCS Install: Find the installationSuccesfullyFinished.dat (SAPINST)"
#   ansible.builtin.find:
#     paths:                             "{{ tmp_directory }}/{{ sid_to_be_deployed.sid | upper }}/sapinst_instdir/{{ bom.product_ids.scs.replace('.', '/').replace('/ABAP', '').split(':')[1] }}/INSTALL/DISTRIBUTED/ABAP/ASCS"
#     file_type:                         file
#     patterns:                          'installationSuccesfullyFinished.dat'
#     recurse:                           true
#   register:                            scs_installed_according_to_sapinst

# - name:                                "SCS Install: show"
#   ansible.builtin.debug:
#     var:                               scs_installed_according_to_sapinst
#     verbosity:                         2

# - name:                                "SCS Install: flag"
#   ansible.builtin.file:
#     path:                              "/etc/sap_deployment_automation/{{ sid_to_be_deployed.sid | upper }}/sap_deployment_scs.txt"
#     state:                             touch
#     mode:                              0755
#   when:
#     - scs_installed_according_to_sapinst is defined
#     - scs_installed_according_to_sapinst | length > 0

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

- name:                                "SCS 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_scs.txt"
  register:                            scs_installed
  when:                                "'scs' in supported_tiers"

- name:                                "SCS Install: check if installed"
  ansible.builtin.debug:
    var:                               scs_installed
    verbosity:                         2

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

- name:                                "SCS Install: register variables"
  ansible.builtin.set_fact:
    scs_bom_id:                        "{{ bom.product_ids.scs }}"
    scs_bom_instance_type:             "{% if bom.InstanceType is defined %}{{ bom.InstanceType | upper }}{% else %}ABAP{% endif %}"

- name:                                "SCS Install: register additional variables"
  ansible.builtin.set_fact:
    installGateway:                    "{% if scs_bom_instance_type == 'ABAP' %}true{% else %}false{% endif %}"

- name:                                "SCS Install"
  block:

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

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

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

    - name:                            "SCS 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_scs_hostname:              "{{ scs_virtual_hostname }}"
        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 }}"
        set_ascsInstallGateway:        "{{ installGateway | bool | lower }}"
        set_ascsInstallWebDispatcher:  "{{ ascsInstallWebDispatcher | default(false) | bool | lower }}"

    - name:                            "SCS Install: install variables"
      ansible.builtin.debug:
        msg:
          - "INSTALLED:  {{ scs_installed.stat.exists }}"
          - "INIFILE:    {{ sap_inifile }}"
          - "PRODUCT ID: {{ bom.product_ids.scs }}"
          - "INSTANCE:   {{ sid_to_be_deployed.ascs_inst_no }}"
          - "MEDIA:      {{ target_media_location }}"
          - "HOST:       {{ scs_virtual_hostname }}"
          - "SID:        {{ sid_to_be_deployed.sid | upper }}"

    - name:                            "SCS Install: Default instance type"
      ansible.builtin.set_fact:
        instance_type:                 "ASCS"
      when:                            bom.InstanceType is not defined

    - name:                            "SCS Install: register instance type"
      ansible.builtin.set_fact:
        instance_type:  >-
                                        {%- set _instance_type = 'ASCS' -%}
                                        {%- if bom.InstanceType == 'JAVA' -%}
                                        {%- set _instance_type = 'SCS' -%}
                                        {%- elif bom.InstanceType == 'ABAP' -%}
                                        {%- set _instance_type = 'ASCS' -%}
                                        {%- else -%}
                                        {%- set _instance_type = 'ASCS' -%}
                                        {%- endif -%}
                                        {{- _instance_type -}}
        public:                        true
      when:                            bom.InstanceType is defined

    - name:                            "SCS Install: register variables"
      ansible.builtin.set_fact:
        scs_bom_instance_type:         "{% if bom.InstanceType is defined %}{{ bom.InstanceType }}{% else %}ABAP{% endif %}"
        public:                        true

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

    - name:                            "SCS Install: Comment out required message server prots in /etc/services"
      ansible.builtin.replace:
        path:                          /etc/services
        regexp:                        '^([a-z\-]+\s+36{{ scs_instance_number }}/.*)$'
        replace:                       '# \1'
        backup:                        true

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

    - name:                            "SCS Install: Assign ownership"
      ansible.builtin.file:
        path:                          "{{ item.path }}"
        owner:                         '{{ sid_to_be_deployed.sidadm_uid }}'
        group:                         sapsys
        recurse:                       true
        state:                         directory
      loop:
        - { path: '/sapmnt/{{ sap_sid | upper }}' }
        - { path: '/usr/sap/{{ sap_sid | upper }}' }

    - name:                            "SCS Install: Progress"
      ansible.builtin.debug:
        msg:                           "Start SCS Installation"

    - name:                            "SCS Install: SAP SCS Install on {{ scs_virtual_hostname }}"
      ansible.builtin.shell: |
                                       umask {{ custom_umask | default('022') }} ;
                                       ./sapinst SAPINST_INPUT_PARAMETERS_URL={{ dir_params }}/{{ sap_inifile }}  \
                                                 SAPINST_EXECUTE_PRODUCT_ID={{ bom.product_ids.scs }}             \
                                                 SAPINST_SKIP_DIALOGS=true                                        \
                                                 SAPINST_USE_HOSTNAME={{ scs_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_scs.txt"
      environment:
        SAPSYSTEMNAME:                 "{{ sid_to_be_deployed.sid | upper }}"
        TMPDIR:                        "{{ tmp_directory }}/{{ sid_to_be_deployed.sid | upper }}"
      register:                        scs_installation
      failed_when:                     scs_installation.rc > 0

    - name:                            "SCS Install: Cleanup ini file {{ ansible_hostname }}"
      ansible.builtin.file:
        path:                          "{{ dir_params }}/{{ sap_inifile }}"
        state:                         absent

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

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

    - name:                            "SCS Install: Find the installationSuccesfullyFinished.dat (SAPINST)"
      ansible.builtin.find:
        paths:                         "{{ tmp_directory }}/{{ sid_to_be_deployed.sid | upper }}/sapinst_instdir/{{ bom.product_ids.scs.replace('.', '/').replace('/ABAP', '').split(':')[1] }}/INSTALL/DISTRIBUTED/{{ scs_bom_instance_type }}/ASCS"
        file_type:                     file
        patterns:                      'installationSuccesfullyFinished.dat'
        recurse:                       true
      register:                        scs_installed_according_to_sapinst

    - name:                            "SCS Install: show"
      ansible.builtin.debug:
        var:                           scs_installed_according_to_sapinst
        verbosity:                     2

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

  when:
    - "'scs' in supported_tiers"
    - not scs_installed.stat.exists

- name:                                "SCS Install status"
  block:

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

    - name:                            "SCS: - return value"
      ansible.builtin.set_fact:
        scs_already_installed:         true
  when:
    - scs_installed.stat.exists

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