---
- name: Splunk Forwarder Install/Upgrade Playbook
  hosts: all
  become: true
  vars:
    splunk_tar_local: "/tmp/splunkforwarder-10.6.0.5-86587d4e3b27-linux-amd64.tgz"
    splunk_tar_remote: "/tmp/splunkforwarder-10.6.0.5-86587d4e3b27-linux-amd64.tgz"
    splunk_tar_sha512: "71567db84c245defd475f11ce0e2826c96bf248a7170f38280d2c78d4ad97fab76237dbb19ed3237c0df275036acb268990a7855641c00bb25096b98d8d3e95e"
    splunk_service_name: "SplunkForwarder"
    splunk_install_path: "/opt/splunkforwarder"

  tasks:
    - name: Display Splunk version file content
      ansible.builtin.command:
        cmd: "cat {{ splunk_install_path }}/etc/splunk.version"
      register: splunk_version
      changed_when: false

    - name: Print version to console
      ansible.builtin.debug:
        var: splunk_version.stdout_lines

    - name: Verify SHA512 checksum of copied tarball
      ansible.builtin.shell:
        cmd: "sha512sum {{ splunk_tar_remote }} | awk '{print $1}'"
      register: sha512sum_result
      changed_when: false

    - name: Check if SHA512 checksum matches
      ansible.builtin.assert:
        that:
          - sha512sum_result.stdout == splunk_tar_sha512
        fail_msg: "SHA512 checksum mismatch for {{ splunk_tar_remote }}"


    - name: Force stop Splunk with its own command if still running
      ansible.builtin.command:
        cmd: "{{ splunk_install_path }}/bin/splunk stop"
      changed_when: false
      ignore_errors: true


    - name: Extract Splunk tarball to /opt
      ansible.builtin.unarchive:
        src: "{{ splunk_tar_remote }}"
        dest: "/opt/splunkforwarder"
        remote_src: true
        extra_opts:
          - "--strip-components=1"
      when: not ansible_check_mode

    - name: Change ownership of /opt/splunk to splunk user and group
      ansible.builtin.file:
        path: "{{ splunk_install_path }}"
        owner: splunk
        group: splunk
        recurse: true

    - name: Start Splunk and accept license
      ansible.builtin.command:
        cmd: "{{ splunk_install_path }}/bin/splunk start --accept-license --answer-yes --no-prompt"

    - name: Display Splunk version file content
      ansible.builtin.command:
        cmd: "cat {{ splunk_install_path }}/etc/splunk.version"
      register: splunk_version
      changed_when: false

    - name: Print version to console
      ansible.builtin.debug:
        var: splunk_version.stdout_lines

    - name: Remove Splunk tarball from /tmp
      ansible.builtin.file:
        path: "{{ splunk_tar_remote }}"
        state: absent
