#!/usr/bin/env bash
# Compile protobuf files into type files
DIR="${BASH_SOURCE%/*}"
if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi

get_absolute_path () {
  echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
}

set -e

EXTERNAL_DEPENDENCIES=()
PROTO_DIR="$(get_absolute_path "$DIR/../src/.generated")"
PROTO_DEF_DIRS=(
  "$(get_absolute_path "$DIR/../../../definitions")"
  "$(get_absolute_path "$DIR/../definitions")"
  ${EXTERNAL_DEPENDENCIES[@]}
)
PROTO_SCRIPT="$(get_absolute_path "$(npm bin)/protoc-gen-ts_proto")"
PROTO_FILES=()
DIR_OPTIONS=()
for PROTO_DEF_DIR in "${PROTO_DEF_DIRS[@]}"; do
  echo "Finding files for $PROTO_DEF_DIR";
  PROTO_FILES+=($(find "$PROTO_DEF_DIR" -name "*.proto"));
  DIR_OPTIONS+=("-I" "$PROTO_DEF_DIR");
done

if [ -d "$PROTO_DIR" ]; then
  echo "Cleaning previous compilation";
  rm -fr "$PROTO_DIR";
fi
if ! [ -d "$PROTO_DIR" ]; then
  echo "Creating protobuf output directory '$PROTO_DIR'";
  mkdir -p "$PROTO_DIR";
fi

GEN_OPTIONS=(
 "--ts_proto_out=$PROTO_DIR"
 "--ts_proto_opt=esModuleInterop=true"
 "--ts_proto_opt=env=node"
 "--ts_proto_opt=oneof=unions"
 "--ts_proto_opt=unrecognizedEnum=false"
 "--ts_proto_opt=snakeToCamel=false"
 "--ts_proto_opt=lowerCaseServiceMethods=true"
 "--ts_proto_opt=outputServices=generic-definitions,outputServices=default"
)

# We compile/emit twice, since it's cleaner to have a proper type file to reference and the actual implementation file
for file in "${PROTO_FILES[@]}"; do
  echo "Generating protobuf implementation for '$file'"
  $(npm bin)/grpc_tools_node_protoc \
    --plugin "$PROTO_SCRIPT" \
    "${GEN_OPTIONS[@]}" \
    "$file" \
    "${DIR_OPTIONS[@]}" &
done
wait

# Compile denum types from generated types above
ENUM_DIR="$(get_absolute_path "$DIR/../src/types/enums/proto")"
FILES=($(find "$PROTO_DIR" -name "*.ts"))
echo "Decoding C-style enums for project"
for file in "${FILES[@]}"; do
  python "$DIR/denum.py" "$ENUM_DIR" "$file"
done

# Compile encode/decode helpers from generated types/enums
ENCODE_DECODE_DIR="$(get_absolute_path "$DIR/../src/lib/.generated")"
echo "Compiling Encode/Decode helpers for project"
if [ -d "$ENCODE_DECODE_DIR" ]; then
  echo "Cleaning previous compilation";
  rm -fr "$ENCODE_DECODE_DIR";
fi
if ! [ -d "$ENCODE_DECODE_DIR" ]; then
  echo "Creating output directory";
  mkdir -p "$ENCODE_DECODE_DIR";
fi
python "$DIR/encode_decode.py" "$ENCODE_DECODE_DIR" "$PROTO_DIR" "$ENUM_DIR"

echo "Done"
