#!/bin/bash

# Replace root-relative imports generated by grpc_tools.protoc to absolute ones
# Look nbgp/bgp/client.py for the full procedure
# Use:
# replace-protobuf-local-imports.sh [PATH]
# PATH: path to directory with protobuf generated files (DEFAULT: nbgp/bgp/generated)

set -eu
set -o pipefail

ROOT_PATH="$(dirname -- "$(dirname -- "$(realpath "${BASH_SOURCE[0]}")")")"
DIR_PATH="${1:-$ROOT_PATH/nbgp/bgp/generated}"

if [[ ! -d "$DIR_PATH" ]]; then
    echo "The path is not directory" >&2
    exit 1
fi

DIR_PATH="$(realpath "$DIR_PATH")"
PREFIX="$(echo "${DIR_PATH#$ROOT_PATH/}" | tr '/' '.')"

for file in "$DIR_PATH"/*.py ; do
    sed -i -e "s/^import \([^.]*\)_pb2 as \(.*\)_pb2$/import $PREFIX.\1_pb2 as \2_pb2/" "$file"
done
