#!/usr/bin/env bash

if [[ -n "${SECRET_KEY}" ]] && ! grep -q "export SECRET_KEY=" ~/.profile; then
  echo "export SECRET_KEY=${SECRET_KEY}" >> ~/.profile
fi

if [[ -n "${RPC_URL}" ]] && ! grep -q "export RPC_URL=" ~/.profile; then
  echo "export RPC_URL=${RPC_URL}" >> ~/.profile
fi

if [[ -n "${PAYMENT_TOKEN_ADDRESS}" ]] && ! grep -q "export PAYMENT_TOKEN_ADDRESS=" ~/.profile; then
  echo "export PAYMENT_TOKEN_ADDRESS=${PAYMENT_TOKEN_ADDRESS}" >> ~/.profile
fi

if [[ -n "${DATA_PAYMENTS_ADDRESS}" ]] && ! grep -q "export DATA_PAYMENTS_ADDRESS=" ~/.profile; then
  echo "export DATA_PAYMENTS_ADDRESS=${DATA_PAYMENTS_ADDRESS}" >> ~/.profile
fi

if [[ -n "${EVM_NETWORK}" ]] && ! grep -q "export EVM_NETWORK=" ~/.profile; then
  echo "export EVM_NETWORK=${EVM_NETWORK}" >> ~/.profile
fi

CONTACT_PEER="${1:-}"
NETWORK_CONTACTS_URL="${2:-}"
NETWORK_ID="${3:-}"

{% if not testnet_name.startswith('PROD-') %}
CONTACT_PEER_ARG=""
if [ -n "$CONTACT_PEER" ]; then
  CONTACT_PEER_ARG="--peer $CONTACT_PEER"
fi
NETWORK_CONTACTS_URL_ARG=""
if [ -n "$NETWORK_CONTACTS_URL" ]; then
  NETWORK_CONTACTS_URL_ARG="--network-contacts-url $NETWORK_CONTACTS_URL"
fi
if [ -z "$CONTACT_PEER" ] && [ -z "$NETWORK_CONTACTS_URL" ]; then
  echo "No contact peer or network contacts URL provided. Please provide the initial contact peer or network contacts URL."
  exit 1
fi
TESTNET_ARG="--testnet"
{% else %}
CONTACT_PEER_ARG=""
NETWORK_CONTACTS_URL_ARG=""
TESTNET_ARG=""
{% endif %}

NETWORK_ID_ARG=""
if [ -n "$NETWORK_ID" ]; then
  echo "Setting network ID arg to $NETWORK_ID"
  NETWORK_ID_ARG="--network-id $NETWORK_ID"
fi

if ! command -v ant &> /dev/null; then
  echo "Error: 'ant' not found in PATH."
  exit 1
fi

write_metrics_on_success() {
  local time=$1
  local file_size_kb=$2
  metrics_header
  number_of_chunks=$(echo "$stdout" | rg -o 'Number of chunks uploaded: [0-9]+' | rg -o '[0-9]+')
  store_cost=$(echo "$stdout" | rg -o 'Total cost: [0-9]+' | rg -o '[0-9]+' | head -n 1)

  echo "$time,$file_size_kb,$number_of_chunks,$store_cost" >> "./uploader_metrics.csv"
}

write_metrics_on_failure() {
  local time=$1
  local file_size_kb=$2
  metrics_header
  echo "$time,$file_size_kb" >> "./uploader_metrics.csv"
}

metrics_header() {
  if [ ! -f "./uploader_metrics.csv" ]; then
    echo "Total Time(s),File Size (KB),Number of Chunks,Store Cost (AttoTokens)" > "./uploader_metrics.csv"
  fi
}

generate_random_data_file_and_upload() {
  tmpfile=$(mktemp)
  dd if=/dev/urandom of="$tmpfile" bs=100M count=1 iflag=fullblock &> /dev/null

  echo "Generated random data file at $tmpfile"
  file_size_kb=$(du -k "$tmpfile" | cut -f1)

  now=$(date +"%s")
  stdout=$(ant $CONTACT_PEER_ARG $NETWORK_CONTACTS_URL_ARG $TESTNET_ARG $NETWORK_ID_ARG file upload "$tmpfile" 2>&1)
  echo "$stdout"

  if [ $? -eq 0 ]; then
    echo "Successfully uploaded $tmpfile using SAFE CLI"

    file_ref=$(echo "$stdout" | grep -oP 'At address: \K\S+')
    if [ -z "$file_ref" ]; then
      echo "Error: Unable to extract file reference."
    else
      echo "$file_ref" >> "./uploaded_files.log"
    fi

    elapsed=$(($(date +"%s") - $now))
    write_metrics_on_success $elapsed $file_size_kb
  else
    echo "Failed to upload $tmpfile using SAFE CLI"
    elapsed=$(($(date +"%s") - $now))
    write_metrics_on_failure $elapsed $file_size_kb
  fi

  rm "$tmpfile"
}

while true; do
  echo "================================"
  echo "Generating and uploading file..."
  echo "================================"
  echo "$(date +"%A, %B %d, %Y %H:%M:%S")"
  generate_random_data_file_and_upload
  sleep 10
done
