#!/bin/bash

####
# envoy-library-references.sh
#
# This script ensures that all of the protobuf packages present in the
# github.com/envoyproxy/go-control-plane library are referenced in the consul
# codebase somewhere so that the ultimate binary doesn't eliminate those
# packages. When the packages are linked in they use proto.RegisterFile() to
# globally register the types in the protobuf machinery so that they are
# available for decoding.
#
# We primarily need this for the Escape Hatch feature where users can provide
# arbitrary xDS JSON for Consul to decode. If extension points use *any.Any and
# use an extention package that Consul itself doesn't use then it won't decode
# unless the package is linked into the binary.
#
####

set -euo pipefail
unset CDPATH

cd "$(dirname "$0")" # build-support/scripts
cd ../..             # <ROOT>

if [[ ! -f GNUmakefile ]] || [[ ! -f go.mod ]]; then
    echo "not in root consul checkout: ${PWD}" >&2
    exit 1
fi

readonly LIBRARY_VERSION="$(grep github.com/envoyproxy/go-control-plane go.mod | awk '{print $2}')"
readonly OUTFILE=z_xds_packages.go

echo "Fetching envoyproxy/go-control-plane @ ${LIBRARY_VERSION}..."

rm -rf _envoy_tmp
mkdir _envoy_tmp
trap "rm -rf _envoy_tmp" EXIT
(
cd _envoy_tmp

git clone git@github.com:envoyproxy/go-control-plane
cd go-control-plane
git co -b consul-temp "${LIBRARY_VERSION}"

IFS=$'\n' candidates=($(find . -name *.pb.go -a -type f | sed 's@/[^/]*\.pb\.go$@@' | sort -u))

echo "Generating a fresh ${OUTFILE} file..."
cat <<-EOF > "${OUTFILE}"
// Code generated by envoy-library-references.sh. DO NOT EDIT.

package xds

import (
EOF

for cand in "${candidates[@]}"; do
    import_name="${cand#./}"
    echo "	_ \"github.com/envoyproxy/go-control-plane/${import_name}\"" >> "${OUTFILE}"
done

echo ")" >> "${OUTFILE}"

goimports -w "${OUTFILE}"

mv -f "${OUTFILE}" ../../agent/xds
)

echo "updating vendored code..."
make update-vendor
