#!/usr/bin/env bash

USAGE="Usage: $(basename "${0}") {log-group-name} {log-streame-name} {days} {output_file}"

if [ "$#" -ne 4 ]; then
  echo "${USAGE}"
  exit 1
fi

LOG_GROUP_NAME="${1}"
LOG_STREAM_NAME="${2}"
LOG_DAYS="${3}"
LOG_OUTPUT="${4}"

echo "" >"${LOG_OUTPUT}"
next_token=""

while true; do
  #fetch log events using the next token (if available)
  if [ -z "${next_token}" ]; then
    response=$(aws logs get-log-events \
      --log-group-name "${LOG_GROUP_NAME}" \
      --log-stream-name "${LOG_STREAM_NAME}" \
      --start-time "${LOG_DAYS}")
  else
    response=$(aws logs get-log-events \
      --log-group-name "${LOG_GROUP_NAME}" \
      --log-stream-name "${LOG_STREAM_NAME}" \
      --start-time "${LOG_DAYS}" \
      --next-token "${next_token}")
  fi

  # Check if there are no more log events
  if [ -z "${response}" ]; then
    break
  fi

  # Append log events to output file
  echo "${response}" >>"${LOG_OUTPUT}"

  # Extract the next forward token
  last_token="${next_token}"
  next_token=$(echo "${response}" | jq ".nextBackwardToken" | sed 's/"//g')

  last_token_number=$(echo "${last_token}" | cut -d/ -f2)
  next_token_number=$(echo "${next_token}" | cut -d/ -f2)

  if [ "${last_token_number}" = "${next_token_number}" ]; then
    break
  fi
done
