# SPDX-License-Identifier: MIT
---
- name: Ensure that the mssql-server service is started
  service:
    name: mssql-server
    state: started

- name: Check if a custom tcpport setting exist
  command: grep '^tcpport = ' {{ __mssql_conf_path }}
  failed_when: false
  changed_when: false
  register: __mssql_custom_tcp_port

- name: Check if a custom ipaddress setting exist
  command: grep '^ipaddress = ' {{ __mssql_conf_path }}
  failed_when: false
  changed_when: false
  register: __mssql_custom_ip_address

- name: Set a fact with a login command
  vars:
    __ipaddress: >-
      {{ __mssql_custom_ip_address.stdout |
      regex_search('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}') }}
    __tcpport: >-
      {{ __mssql_custom_tcp_port.stdout | regex_search('[1-9][0-9]{0,4}') }}
    __s_arg: >-
      {{ (__ipaddress or __tcpport) | ternary('-S', '') }}
    __ipaddress_arg: >-
      {{ __ipaddress if __ipaddress else '127.0.0.1' if __tcpport else '' }}
  set_fact:
    __mssql_sqlcmd_login_cmd: >-
      /opt/mssql-tools/bin/sqlcmd
      {{ __s_arg }}
      {{ __ipaddress_arg }}{{ ',' if __tcpport
      else '' }}{{ __tcpport if __tcpport else '' }}
      -U sa -P {{ mssql_password | quote }}
  no_log: true
