#!/bin/bash

set -e

cd "$(dirname "$0")"

# Generate synchronous client from the asynchronous client
export skipped_directories=( "connection" )
export skipped_files=( "streams/os.py" "__init__.py" "streams/memory.py" "streams/os.py" "invenio/transfer/multipart.py" )

isSkipped () {
  local fn="$1"
  directory="$(dirname "$fn")"

  for i in "${skipped_directories[@]}"
  do
      if [ "$i" == "$directory" ] ; then
          return 0
      fi
  done

  for i in "${skipped_files[@]}"
  do
      if [ "$i" == "$fn" ] ; then
          return 0
      fi
  done

  return 1
}

removeHeadComments () {
  IFS=""
  removing=1
  while read LINE ; do
    if [[ $removing -eq 1 ]] ; then
      if echo $LINE | egrep "^#.*$" >/dev/null ; then
        continue
      else
        removing=0
      fi
    fi
    echo "$LINE"
  done
}

convertFile () {
  fn="$1"
  ofn="$2"
  odn="$(dirname "$ofn")"
  if [ ! -d "$odn" ]; then
    mkdir -p "$odn"
  fi
  echo "Converting $fn to $ofn"
  cat <<EOF > "$ofn"
#
# This file was generated from the asynchronous client at ${fn} by generate_synchronous_client.sh
# Do not edit this file directly, instead edit the original file and regenerate this file.
#


EOF
  (
    cat "$fn" | \
        sed 's/async def /def /g' | \
        sed 's/async with /with /g' | \
        sed 's/async for /for /g' | \
        sed 's/await //g' | \
        sed 's/asynccontextmanager/contextmanager/g' | \
        sed 's/__aiter__/__iter__/g' | \
        sed 's/__anext__/__next__/g' | \
        sed 's/StopAsyncIteration/StopIteration/g' | \
        sed 's/AsyncIterator/Iterator/g' | \
        sed 's/AsyncIterable/Iterable/g' | \
        sed 's/AsyncGenerator\[T, None\]/Generator[T, None, None]/g' | \
        sed 's/AsyncGenerator/Generator/g' | \
        sed 's/AsyncContextManager/ContextManager/g' | \
        sed 's/async_client/sync_client/g' | \
        sed 's/_async_/_sync_/g' | \
        sed 's/Async/Sync/g' | \
        sed 's/anext/next/g' | \
        sed 's/^import asyncio//' | \
        sed 's/^from asyncio .*$//'
    # need to add newline otherwise the last line will be ignored
    echo
  ) | removeHeadComments >> "$ofn"
}

removePrevious() {
  target_dir="$1"
  (
    cd $target_dir
    find . -name "*py" | sed 's#^\./##' | while read file; do
      if ! isSkipped "$file" ; then
        echo "Removing $file"
        rm "$file"
      fi
    done
  )
}

generateClientPackage () {
  source_dir="$1"
  target_dir="$2"
  (
    cd $source_dir
    find . -name "*py" | sed 's#^\./##' | while read file; do
      if ! isSkipped "$file" ; then
        echo "Converting $file"
        ofn="${file//async/sync}"
        convertFile "$file" "$target_dir/$ofn"
      fi
    done
  )
}

# remove caches
find src -name "__pycache__" -type d -exec rm -rf {} +        || true
find tests/invenio_tests -name "__pycache__" -type d -exec rm -rf {} +  || true
rm -rf tests/__pycache__  || true

async_client_full_path="$PWD/src/nrp_cmd/async_client"
sync_client_full_path="$PWD/src/nrp_cmd/sync_client"

removePrevious "$sync_client_full_path"
generateClientPackage "$async_client_full_path" "$sync_client_full_path"

test_async_client_full_path="$PWD/tests/invenio_tests/async_tests"
test_sync_client_full_path="$PWD/tests/invenio_tests/sync_tests"

test -d "$test_sync_client_full_path" || mkdir -p "$test_sync_client_full_path"
removePrevious "$test_sync_client_full_path"
generateClientPackage "$test_async_client_full_path" "$test_sync_client_full_path"