---
- name: Input with sqlcmd {{ item }}
  block:
    - name: Create a tempfile on the host for {{ item }}
      tempfile:
        state: file
        prefix: "{{ item | basename }}_"
        suffix: .sql
      register: __mssql_sql_tempfile
      changed_when: false

    - name: Copy the file to the host {{ item }}
      copy:
        src: "{{ item }}"
        dest: "{{ __mssql_sql_tempfile.path }}"
        mode: preserve
      when: item is not search(".*\.j2$")
      changed_when: false

    - name: Generate the template on the host for {{ item }}
      template:
        src: "{{ item }}"
        dest: "{{ __mssql_sql_tempfile.path }}"
        mode: preserve
      when: item is search(".*\.j2$")
      changed_when: false

    - name: Input with the sqlcmd command {{ item }}
      command: >-
        {{ __mssql_sqlcmd_login_cmd }} -i {{ __mssql_sql_tempfile.path }} -b
      register: __mssql_sqlcmd_input
      changed_when: '"successfully" in __mssql_sqlcmd_input.stdout'
      no_log: true
      until: >-
        "TCP Provider: Error code 0x68" not in __mssql_sqlcmd_input.stdout and
        "TCP Provider: Error code 0x68" not in __mssql_sqlcmd_input.stderr and
        "TCP Provider: Error code 0x102" not in __mssql_sqlcmd_input.stdout and
        "TCP Provider: Error code 0x102" not in __mssql_sqlcmd_input.stderr and
        "TCP Provider: Error code 0x2749" not in __mssql_sqlcmd_input.stdout and
        "TCP Provider: Error code 0x2749" not in __mssql_sqlcmd_input.stderr
  always:
    # Role prints the output if the input succeeds, otherwise Ansible prints the
    # output from the failed input tasks
    - name: Print file location and output from inputting {{ item }}
      when:
        - >-
          (mssql_debug | bool) or
          (__mssql_sqlcmd_input is failed)
        - __mssql_sqlcmd_loop | length > 0
      debug:
        var: __mssql_sqlcmd_loop
      loop:
        - "{{ __mssql_sql_tempfile.path }}"
        - "{{ __mssql_sqlcmd_input.stdout_lines }}"
        - "{{ __mssql_sqlcmd_input.stderr_lines }}"
      loop_control:
        loop_var: __mssql_sqlcmd_loop

    # Role keeps the file if the input failed
    - name: Remove the tempfile {{ item }}
      file:
        path: "{{ __mssql_sql_tempfile.path }}"
        state: absent
      when:
        - __mssql_sqlcmd_input is succeeded
        - not mssql_debug
      changed_when: false
