#!/usr/bin/env bash
# This script downloads GraphQL fallbacks automatically
# To ensure that your query will have a fallback, use the magic comment before
# the line where you define the query. For example:
# ```
#  # @ensure-fallback
#  query CustomerSupportPhonesQuery {
# ```

function fetchFallbackData {
    # $1: Output file

    # Read GraphQL query string
    read -r -d '' QUERY
    query=`echo $QUERY | tr '\n' ' '`

    # Identify query name
    queryName=` \
      echo $query | sed 's/{//g' | sed -E 's/query ([[:alnum:]]+).*/\1/'`

    # Helpers for formatting request sting
    a='{"query": "'
    b='"}'

    mkdir -p ./src/fallbacks/
    curl \
      -X POST \
      -H "Content-Type: application/json" \
      --data "$a$query$b" \
      https://graphql.kiwi.com/ \
      -o ./src/fallbacks/$queryName.json \
      --silent
}

# Find queries that have the fallback comment
QueriesWithFallbackComment=` \
    grep -A1 "# @ensure-fallback" -r src \
  | grep -v "# @ensure-fallback" \
  | cut -d" " -f1,4 \
  | sed "s/\/index\.js\- /\/__generated__\//" \
  | sed "s/$/.graphql.js/"`

# Execute fallback fetcher for every query that needs it
echo $QueriesWithFallbackComment | while read fileName
do
    if [ ! -z "$fileName" ]; then
      echo "Creating fallback data for $fileName"
      cat $fileName \
        | tr -d '\n' \
        | sed 's/^.*\/\*\:\:.*\*\/\/\*//' \
        | sed 's/\*\/.*$//' \
        | grep -v "^$" \
        | fetchFallbackData
    fi
done
