#!/bin/bash

set -v

# Set the log group name and log stream name
log_group_name="nexus_nonprod_apache_logs"
log_stream_name="nexus-nonprod(i-0fa628054b51076a5)"

# Initialize the next token
next_token="f/38115116396761646301913209929933491070454673106305352283/s"

# Loop until the timestamp is before 28/Feb/2024
while true; do
  echo "DEBUG: next_token = ${next_token}"
  # Run the AWS CLI command to retrieve log events
  response=$(aws logs get-log-events --log-group-name "$log_group_name" --log-stream-name "$log_stream_name" --next-token "$next_token")
  echo "DEBUG: respose = ${response}"

  # Extract the next token and timestamp from the response
  next_token=$(echo "$response" | jq -r '.nextBackwardToken')
  timestamp=$(echo "$response" | jq -r '.events[-1].timestamp')

  # Convert the timestamp to human-readable format
  echo "DEBUG: timestamp = ${timestamp}"
  date_string=$(date -r "$((timestamp / 1000))" "+%d/%b/%Y")

  # Append the log events to the log file
  echo "$response" >>~/Downloads/btime.log

  # Print the last line of the log file
  tail ~/Downloads/btime.log

  # Check if the timestamp is before 28/Feb/2024
  if [[ $date_string < "28/Feb/2024" ]]; then
    break
  fi
done
