# SPDX-License-Identifier: MIT
---
# To run this test, AD server must be configured and it's properties
# provided with the following variables:
# ad_integration_realm
# ad_integration_user
# ad_integration_password
# Inventory must contain the client Linux node and the ad AD Server node like:
# all:
#   hosts:
#     client:
#       ansible_connection: local
#       ansible_host: 127.0.0.1
#     ad:
#       ansible_host: 10.192.1.1
#       ad_fqdn: ad1.domain.com
#       ansible_connection: winrm
#       ansible_password: Secret123
#       ansible_port: 5986
#       ansible_user: Administrator
#       ansible_winrm_server_cert_validation: ignore
- name: Test integration with AD server
  hosts: client
  vars:
    mssql_accept_microsoft_odbc_driver_for_sql_server_eula: true
    mssql_accept_microsoft_cli_utilities_for_sql_server_eula: true
    mssql_accept_microsoft_sql_server_standard_eula: true
    mssql_version: 2022
    mssql_password: "p@55w0rD"
    mssql_edition: Evaluation
    mssql_manage_firewall: true
    mssql_debug: true
    mssql_ad_configure: true
    mssql_ad_sql_user: sqluser
    mssql_ad_sql_password: "p@55w0rD1"
    ad_integration_realm: domain.com
    ad_integration_user: Administrator
    ad_integration_password: Secret123
    ad_integration_manage_dns: true
    ad_integration_dns_server: 1.1.1.1
    ad_integration_dns_connection_name: eth0
    ad_integration_dns_connection_type: ethernet
    # ad_integration_realm is randomized in IDM CI hence need to use variables
    # Cannot use variable for Administrator because test with
    # mssql_ad_join: false does ad_integration_user: null
    __mssql_ad_login: >-
      {{ ad_integration_realm.split('.') | first + '\Administrator' }}
    mssql_post_input_sql_content: |-
      USE master;
      IF NOT EXISTS (
        SELECT name FROM sys.server_principals
        WHERE name = '{{ __mssql_ad_login }}'
      )
      BEGIN
        PRINT 'A {{ __mssql_ad_login }} login does not exist, creating';
        CREATE LOGIN [{{ __mssql_ad_login }}] FROM WINDOWS;
        PRINT 'The {{ __mssql_ad_login }} login created successfully';
      END
      ELSE
      BEGIN
        PRINT 'A {{ __mssql_ad_login }} login already exists, skipping'
      END

  tasks:
    - name: Set up MSSQL and configure AD authentication with keytab
      vars:
        # /tmp/mssql.keytab is created in tests_ad_integration.yml
        mssql_ad_keytab_file: /tmp/mssql.keytab
        mssql_ad_keytab_remote_src: false
        mssql_ad_sql_password: null
      include_role:
        name: linux-system-roles.mssql

    - name: Test AD integration
      include_tasks: ../tasks/verify_ad_auth.yml

    - name: Clean up after the role invocation
      include_tasks: ../tasks/cleanup.yml
