#!/bin/bash

# Initialize an empty array to store the names
names=()

# Read the names from the names.txt file into the array
while IFS= read -r line; do
  names+=("$line")
done < names.txt

# Loop through each name
for name in "${names[@]}"; do
  # Update the Cargo.tom file with the new name
  sed "s/^name = .*/name = \"$name\"/" Cargo.toml > Cargo.toml.tmp && mv Cargo.toml.tmp Cargo.toml

  # Try to publish the crate
  output=$(cargo publish --allow-dirty 2>&1)
  # output="the remote server responded with an error (status 429 Too Many Requests): You have published too many new crates in a short period of time. Please try again after Mon, 08 Jul 2024 02:25:00 GMT or email help@crates.io to have your limit increased. "

  echo "$output"

convert_to_timestamp() {
  python3 -c "
from datetime import datetime
import sys
try:
    dt = datetime.strptime('$1'.strip(), '%a, %d %b %Y %H:%M:%S GMT')
    print(int(dt.timestamp()))
except ValueError as e:
    print(f'Error: {e}', file=sys.stderr)
    sys.exit(1)
  "
}


  # Check if the output contains the rate limit error
  if echo "$output" | grep -q "status 429 Too Many Requests"; then
    # Extract the retry time from the output
    retry_time=$(echo "$output" | grep -o 'after .* GMT' | awk '{for (i=2; i<=NF; i++) printf $i" "; print ""}')

    # Get the current time in GMT
    current_time=$(date -u +"%a, %d %b %Y %H:%M:%S GMT")

    # Convert both times to Unix timestamps
    retry_timestamp=$(convert_to_timestamp "$retry_time")
    current_timestamp=$(convert_to_timestamp "$current_time")

    # Calculate the wait time in seconds
    wait_time=$((retry_timestamp - current_timestamp))

    # Wait until the retry time
    echo "Rate limit reached. Waiting until $retry_time to retry..."
    sleep $wait_time

    # Retry publishing the crate after the wait time
    output=$(cargo publish --allow-dirty 2>&1)
    echo "$output"
  fi
done