#!/bin/sh

nodejs() {
  echo "Generating NodeJS pb files from protobuf files..."
  echo "  Installing grpc-tools..."
  if (npm i grpc-tools --quiet --no-progress --silent); then
    echo '    Install grpc-tools Success'; echo '';
    echo "  Generating NodeJS stubs..."
    if (npx grpc_tools_node_protoc --js_out=import_style=commonjs,binary:nodejs-client/ --grpc_out=grpc_js:nodejs-client/ $(find services -name "*.proto")); then
      echo '    Generate NodeJS stubs Success'; echo '';
      echo "  Copying proto files into ./nodejs-client/ as they are needed in the nodejs-client package..."
      for s in $(find services -name "*.proto"); do
        echo "    Copy $s --> nodejs-client/$s"
        cp "$s" nodejs-client/"$s"
      done
    else
      echo '    Generate NodeJS stubs Failure'; echo '';
      exit 1
    fi
  else
    echo '    Install grpc-tools Failure'; echo '';
  fi
}

golang() {
  if (make gen_proto); then
    echo '  Generate Golang stubs Success'; echo '';
  else
    echo '  Generate Golang stubs Failure'; echo '';
    exit 1
  fi
}

java() {
  for s in $(find services -name "*.proto"); do
    echo "    Copy $s --> java/client/src/main/proto/$s"
    out_file=java/client/src/main/proto/"$s"
    mkdir -p $(dirname $out_file)
    cp "$s" "$out_file"
  done
  if (cd java/client && mvn clean install -q); then
    echo '  Generate Java stubs Success'; echo '';
  else
    echo '  Generate Java stubs Failure'; echo '';
    exit 1
  fi
}

if [[ "$1" == "all" ]] || [[ "$1" == "" ]]; then
  nodejs
  echo
  golang
  echo
  java
elif [[ "$1" == "golang" ]]; then
  golang
elif [[ "$1" == "nodejs" ]]; then
  nodejs
elif [[ "$1" == "java" ]]; then
  java
else
  echo "Generate language-specific gRPC client files."
  echo "Usage: $(basename $0) {all|nodejs|golang|java} [default: all]"
  exit 0
fi
