---
- name: Splunk Install/Upgrade Playbook
  hosts: all
  become: true
  vars:
    splunk_tar_local: "/tmp/splunk-10.6.0.5-86587d4e3b27-linux-amd64.tgz"
    splunk_tar_remote: "/tmp/splunk-10.6.0.5-86587d4e3b27-linux-amd64.tgz"
    splunk_tar_sha512: "c5f26fedc65b3959d63283106560f4318131357d3239404d8f12f18415a31901a6dc7357e04167eb840de73995b0100435ad09a1ded08674a6ec2a4f05337643"
    splunk_service_name: "Splunkd"
    splunk_install_path: "/opt/splunk"

  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/splunk"
        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