#!/usr/bin/env bash
set -euo pipefail

USAGE='Usage: '"$(basename "${0}")"' {log-group-name} {log-stream-name} {start-time-ms} {output_file}'

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

LOG_GROUP_NAME=$1
LOG_STREAM_NAME=$2
START_TIME_MS=$3
LOG_OUTPUT=$4

# Truncate (or create) the output file
: >"${LOG_OUTPUT}"

next_token=""

while true; do
  # Build the base command
  if [[ -z ${next_token} ]]; then
    # First page
    if ! response=$(aws logs get-log-events \
      --log-group-name "${LOG_GROUP_NAME}" \
      --log-stream-name "${LOG_STREAM_NAME}" \
      --start-time "${START_TIME_MS}" \
      --start-from-head \
      2>&1); then
      echo "Error: Failed to retrieve log events: ${response}" >&2
      exit 1
    fi
  else
    # Subsequent pages
    if ! response=$(aws logs get-log-events \
      --log-group-name "${LOG_GROUP_NAME}" \
      --log-stream-name "${LOG_STREAM_NAME}" \
      --start-time "${START_TIME_MS}" \
      --next-token "${next_token}" \
      --start-from-head \
      2>&1); then
      echo "Error: Failed to retrieve log events: ${response}" >&2
      exit 1
    fi
  fi

  # Stop if nothing came back (paranoia guard)
  if [[ -z ${response} ]]; then
    break
  fi

  # Append raw response JSON to the output file
  echo "${response}" >>"${LOG_OUTPUT}"

  # Advance the token; break if it stops changing
  last_token="${next_token}"
  next_token=$(echo "${response}" | jq -r '.nextForwardToken // empty')

  if [[ -z ${next_token} || ${last_token} == "${next_token}" ]]; then
    break
  fi
done
