#!/usr/bin/env bash

set -e

cd "$(dirname "$0")/.."

BUILD_DIR="${PWD}/.build"

if [[ ! -d "${BUILD_DIR}" ]]; then
    mkdir -p "${BUILD_DIR}"
fi


# Put our temp files in the poetry build directory
TMPDIR="${BUILD_DIR}/protofixup"
echo "Fixing up protobuf paths in ${TMPDIR} temp directory"

# Ensure a clean build
[ -e "${TMPDIR}" ] && rm -r "${TMPDIR}"

INDIR="${TMPDIR}/in/meshtastic/aiomeshtastic/protobuf"
OUTDIR="${TMPDIR}/out"
PYIDIR="${TMPDIR}/out"
mkdir -p "${OUTDIR}" "${INDIR}" "${PYIDIR}"
cp "${PWD}/protobufs/meshtastic/"*.proto "${INDIR}"
cp "${PWD}/protobufs/nanopb.proto" "${INDIR}"

# OS-X sed is apparently a little different and expects an arg for -i
if [[ $OSTYPE == 'darwin'* ]]; then
  if which gsed >/dev/null; then
    SEDCMD="gsed -i -E"
  else
    SEDCMD="sed -i '' -E"
  fi
else
	SEDCMD="sed -i -E"
fi


# change the package names to meshtastic.aiomeshtastic.protobuf
$SEDCMD 's/^package meshtastic;/package meshtastic.aiomeshtastic.protobuf;/' "${INDIR}/"*.proto
# fix the imports to match
$SEDCMD 's/^import "meshtastic\//import "meshtastic\/aiomeshtastic\/protobuf\//' "${INDIR}/"*.proto
# adjust nanopb
$SEDCMD 's/^import "nanopb.proto";/import "meshtastic\/aiomeshtastic\/protobuf\/nanopb.proto";/' "${INDIR}/"*.proto

# Generate the python files
protoc -I="$TMPDIR/in" --python_out "${OUTDIR}" "--mypy_out=${PYIDIR}" "${INDIR}/"*.proto

# Change to relative imports
$SEDCMD 's/^from meshtastic.aiomeshtastic.protobuf import/from . import/' "${OUTDIR}/meshtastic/aiomeshtastic/protobuf/"*pb2*.py
$SEDCMD 's/^import meshtastic.aiomeshtastic.protobuf.(.*)$/from . import \1/' "${OUTDIR}/meshtastic/aiomeshtastic/protobuf/"*pb2*.pyi
$SEDCMD 's/\: meshtastic.aiomeshtastic.protobuf./: /' "${OUTDIR}/meshtastic/aiomeshtastic/protobuf/"*pb2*.*
$SEDCMD 's/-> meshtastic.aiomeshtastic.protobuf./-> /' "${OUTDIR}/meshtastic/aiomeshtastic/protobuf/"*pb2*.*
$SEDCMD 's/\[meshtastic.aiomeshtastic.protobuf./[/' "${OUTDIR}/meshtastic/aiomeshtastic/protobuf/"*pb2*.*



PROTOBUF_VERSION=$(cd "${PWD}/protobufs" && git tag --points-at HEAD | sed 's/v\(.*\)/\1/')
# Create a __init__.py in the out directory with protobuf version
cat <<EOT > "${OUTDIR}/meshtastic/aiomeshtastic/protobuf/__init__.py"
__version__ = "$PROTOBUF_VERSION"
EOT

# Copy to the source controlled tree
mkdir -p custom_components/meshtastic/aiomeshtastic/protobuf
rm -rf custom_components/meshtastic/aiomeshtastic/protobuf/*pb2*.py
cp "${OUTDIR}/meshtastic/aiomeshtastic/protobuf"/* custom_components/meshtastic/aiomeshtastic/protobuf

exit 0