  - name: Install packages to scan
    shell: apt -y install {{ packages_to_scan }} || true

  - name: Create key and cert directory
    shell: mkdir -p {{ key_and_cert_dir }}

  - name: Create key and cert files
    # echo -e because the string contains "\n" characters
    shell: 'echo "{{ slapos_key }}" > {{ key_and_cert_dir }}/key; echo "{{ slapos_cert }}" > {{ key_and_cert_dir }}/certificate'

  - name: Create configuration from template
    shell: "sed '{{conf_regex}}' {{conf}}.in > {{conf}}"


  - name: save fluentbit conf
    shell: cat {{conf}}
    register: fluentbit_conf_content

  - name: print fluentbit conf to a console
    debug:
      msg: "{{ fluentbit_conf_content.stdout }}"

  - name: Launch fluent-bit
    shell: "{{flb}} -e {{plugin}} -c {{conf}} 2>fluentbit.log&"

  - name: Pre-scan
    shell: 'sleep 60; echo "{\"beginning_date\": \"{{ ansible_date_time.iso8601 }}\"}" >> {{log}}'

  - name: Scan /sbin
    shell: "{{mca}} /sbin {{log}}"

  - name: Scan /bin
    shell: "{{mca}} /bin {{log}}"

  - name: Post-scan
    shell: 'echo "{\"end_date\": \"{{ ansible_date_time.iso8601 }}\", \"end_marker\": \"fluentbit_end\"}" >> {{log}}'

  - name: display fluentbit log
    shell: cat fluentbit.log
    register: fluentbit_log_content

  - name: Print the fluentbit log content to a console
    debug:
      msg: "{{ fluentbit_log_content.stdout }}"

  - name: get fluent-bit pid
    shell: 'pidof fluent-bit'
    register: fluentbit_pid

  - name: Print the fluentbit log content to a console
    debug:
      msg: "{{ fluentbit_pid.stdout }}"


  - name: check state
    block:
      - name: Wait fluent-bit
        ansible.builtin.wait_for:
          timeout: 600
          path: /proc/{{fluentbit_pid.stdout}}/status
          state: absent
        when: fluentbit_pid != ""

      - name: print success flag
        ansible.builtin.debug:
          msg: "Build successful, connect to:"

    rescue:
      - name: print failed flag
        ansible.builtin.debug:
          msg: "FATAL: all hosts have already failed -- aborting"
