#!/bin/bash

fail() {
  # Restore stdout by pointing it to fd 3 and send any errors to it
  exec >&3
  [[ -e $tmp ]] && cat "$tmp"

  exit 1
}

cleanup() {
  for f in "${temp_files[@]}"; do
    [[ -e $f ]] && rm -- "$f"
  done
}

temp_files=()

# Clone, i.e. preserve, original stdout using fd 3.
exec 3>&1
# Send stderr and stdout to a temp file
tmp="$(mktemp)"
temp_files+=("$tmp")
exec &>"$tmp"

# Run the fail() method on error
trap fail ERR

# Otherwise cleanup
trap cleanup EXIT

while [[ $1 ]]; do
  case "$1" in
    '-d'|'--directory')
      metrics_directory="$2"
      ;;
    '-r'|'--retention-days')
      retention_days="$2"
  esac
  shift 2
done



# Guard against deleting or archiving files outside of a Puppet service metrics directory.
valid_paths=(puppetserver puppetdb orchestrator ace bolt activemq postgres system_processes system_memory system_cpu vmware)

# Arguments and defaults.
metrics_directory="${metrics_directory:-/opt/puppetlabs/puppet-metrics-collector/puppetserver}"
retention_days="${retention_days:-90}"

# Parameter expansion to strip everything before the last '/', giving us the basename.
metrics_type="${metrics_directory##*/}"

# Check that $metrics_directory ends in a Puppet service.
paths_regex="$(IFS='|'; echo "${valid_paths[*]}")"
[[ $metrics_directory =~ ${paths_regex}$ ]] || {
  echo "Error: Invalid metrics directory. Must end in one of: $(echo -n "${valid_paths[@]}")."
  fail
}

# Delete files in a Puppet service metrics directory older than the retention period, in days.
find "$metrics_directory" -type f -mtime +"$retention_days" -delete

# Compress the remaining files in a Puppet service metrics directory.
# Store the list of files in a temp file so that `tar` and `rm` will operate on the same files
metrics_tmp="$(mktemp)"
temp_files+=("$metrics_tmp")
find "$metrics_directory" -type f -name "*json" >"$metrics_tmp"
tar --create --gzip --file "${metrics_directory}/${metrics_type}-$(date +%Y.%m.%d.%H.%M.%S).tar.gz" \
  --files-from "$metrics_tmp"

# Cleanup the backed up json files so that we do not duplicate files in the tarballs.
# We can assume that the json files have no spaces as they are created by our scripts
# Only run xargs if the file is >0 bytes
[[ -s $metrics_tmp ]] && xargs -a "$metrics_tmp" rm
exit 0
