#!/bin/bash

unset LD_LIBRARY_PATH

filename='splunk_linux_installer_9.1.4.tgz'
local_url='https://splunk.awscloud.anm.com/installers/splunkforwarder-9.1.4-download-Linux-x86_64.tgz'
remote_url="https://download.splunk.com/products/universalforwarder/releases/9.1.4/linux/splunkforwarder-9.1.4-a414fc70250e-Linux-x86_64.tgz"
logfile="/tmp/splunk_upgrade.log"

# check if running as root
if [ "$(id -u)" != "0" ]; then
  echo "This script must be run as root"
  exit 1
fi

function log( ) {
    echo "$(date +"%F %T") severity=\"$1\" msg=\"$2\""
    echo "$(date +"%F %T") severity=\"$1\" msg=\"$2\"" >> $logfile
}

target_version='9.1.4'
#check if version file exists
type="INSTALL"
if [ ! -f /opt/splunkforwarder/etc/splunk.version ]; then
  current_version='NEEDS_INSTALL'
else
  # using lookbehind regex (?<=) to capture just the numeric part of the version
  current_version=$(cat /opt/splunkforwarder/etc/splunk.version | grep -oP "(?<=VERSION=)\S+")
  type="UPGRADE"
  log INFO "Splunk version file found, current version is ${current_version}"
fi



if [ "$current_version" != "$target_version" ]; then
  log "INFO" "Current version $current_version different than $target_version. Will attempt $type."
  log "INFO" "Attempting download from $local_url." 

  wget -q --no-check-certificate $local_url -O $filename

  if [ $? -ne 0 ]; then
    log "WARN" "Unable to download from local server now trying $remote_url"
    wget -q --no-check-certificate $remote_url -O $filename

    if [ $? -ne 0 ]; then
      log "ERROR" "Unable to download installer from any location, exiting"
      exit 1
    fi
  fi

  log "INFO" "installer downloaded, starting $type."
  tar -xzf $filename -C /opt

  # If this is an INSTALL then we need to set the password and deployment server and restart
  if [ "$type" == "INSTALL" ]; then
    # generate random password
    PASSWORD=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 25 | head -n 1)
    /opt/splunkforwarder/bin/splunk enable boot-start -user root --accept-license --answer-yes --no-prompt -systemd-managed 0 --seed-passwd $PASSWORD
    /opt/splunkforwarder/bin/splunk set deploy-poll "spl-cloud-mgr:8089" --accept-license --answer-yes --no-prompt -auth admin:$PASSWORD
    /opt/splunkforwarder/bin/splunk restart --answer-yes --no-prompt --accept-license 
  else
    /opt/splunkforwarder/bin/splunk restart --answer-yes --no-prompt --accept-license

  fi
  log "INFO" "Splunk $type complete."
else
  log "INFO" "Current version $current_version same as $target_version. No action taken."

fi