#!/bin/bash

# *** RUN THIS FROM THE ROOT OF THE PROJECT ***

BASE_DIR=./cashu/lightning/lnd_grpc/protos
echo "base dir: $BASE_DIR"

# Check if the googleapis directory exists
if [ -d "$BASE_DIR/googleapis" ]; then
  echo "$BASE_DIR/googleapis directory already exists. Skipping clone."
else
  echo "Cloning googleapis..."
  echo "If this doesn't work, clone it manually."
  git clone https://github.com/googleapis/googleapis.git $BASE_DIR/googleapis
fi

echo "Installing pip packages..."
poetry add grpcio grpcio-tools googleapis-common-protos mypy-protobuf types-protobuf

echo "curl-ing protos"
curl -o $BASE_DIR/lightning.proto -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/lnrpc/lightning.proto
curl -o $BASE_DIR/router.proto -s https://raw.githubusercontent.com/lightningnetwork/lnd/master/lnrpc/routerrpc/router.proto

echo "auto-generate code from protos..."
python -m grpc_tools.protoc --proto_path=$BASE_DIR/googleapis:$BASE_DIR --mypy_out=$BASE_DIR --python_out=$BASE_DIR --grpc_python_out=$BASE_DIR $BASE_DIR/lightning.proto
python -m grpc_tools.protoc --proto_path=$BASE_DIR/googleapis:$BASE_DIR --mypy_out=$BASE_DIR --python_out=$BASE_DIR --grpc_python_out=$BASE_DIR $BASE_DIR/router.proto

echo "fixing imports on autogenerated files..."
for file in $BASE_DIR/*.{py,pyi}; do
  if [ -f "$file" ]; then
    sed -i -e 's/lightning_pb2/cashu.lightning.lnd_grpc.protos.lightning_pb2/g' -e 's/router_pb2/cashu.lightning.lnd_grpc.protos.router_pb2/g' $file
  fi
done

echo "Done!"

