#!/bin/sh -x 

tar xf /dev/stdin

OUTDIR=src/python_pachyderm/
mkdir -p $OUTDIR

for i in $(find ./proto/pachyderm/src -name "*.proto"); do \
    # Make sure to remove the gogoproto line, as that is go specific
    sed -i s/import.*gogo.proto.*\;// $i
    sed -i 's/\[.*gogoproto.*\]//' $i
    # We need to do this in a pass before compilation because it's not guaranteed we
    # traverse the proto files in order of dependence
done

# fix imports to be relative to src/
for i in $(find ./proto/pachyderm/src -name "*.proto" | grep -v "proto/pachyderm/src/internal"); do \
    perl -pi.bak -e 's/import "((?!google).*)"/import "src\/$1"/' $i
done

# skip pkg and server because protos in there aren't part of the public API
for i in $(find ./proto/pachyderm/src -name "*.proto" | grep -v "proto/pachyderm/src/internal" | grep -v 'proto/pachyderm/src/server'); do \
    python3 -m grpc_tools.protoc -I./proto/pachyderm --python_out=$OUTDIR --grpc_python_out=$OUTDIR ${i}; \
done

for i in $(find $OUTDIR -regex ".*pb2.*py"); do
    # Fix the imports so they work once this is packaged by pypi
    sed -i 's/from src\./from python_pachyderm\.proto\./' $i
done


find $OUTDIR -regex ".*pb2.*py" | xargs tar cf -
