#!/bin/bash

set -euo pipefail

unset CDPATH

cd "$(dirname "$0")"

###
# This script will update the default image names to the latest released versions of
# Consul CE, Consul Enterprise, and Consul Dataplane.
#
# For Envoy, it will interrogate the latest version of Consul for it's maximum supported
# Envoy version and use that.
###

readonly consul_latest="hashicorp/consul:latest"
readonly dataplane_latest="hashicorp/consul-dataplane:latest"

# First pull current versions of some images.
docker pull "$consul_latest" || true
docker pull "$dataplane_latest" || true

# Read the version from the easy ones directly out of their image labels.
consul_version="$(docker image inspect "$consul_latest" | jq -r '.[0].Config.Labels."org.opencontainers.image.version"')"
dataplane_version="$(docker image inspect "$dataplane_latest" | jq -r '.[0].Config.Labels.version')"

# Check to see what version of Envoy consul wants.
docker rm -f consul-envoy-check &>/dev/null || true
docker run -d --name consul-envoy-check "$consul_latest"

envoy_version=""
while true; do
    # We have to retry in case consul doesn't fully start up before we get here.
    set +e
    envoy_version="$(docker exec consul-envoy-check sh -c 'wget -q localhost:8500/v1/agent/self -O -' | jq -r '.xDS.SupportedProxies.envoy[0]')"
    set -e
    if [[ -n "$envoy_version" ]]; then
        break
    fi
done
docker rm -f consul-envoy-check &>/dev/null || true

cat > topology/default_versions.go <<EOF
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1

// Code generated by update-latest-versions.sh. DO NOT EDIT.

package topology

const (
    DefaultConsulCEImage         = "hashicorp/consul:${consul_version}"
    DefaultConsulEnterpriseImage = "hashicorp/consul-enterprise:${consul_version}-ent"
    DefaultEnvoyImage            = "envoyproxy/envoy:v${envoy_version}"
    DefaultDataplaneImage        = "hashicorp/consul-dataplane:${dataplane_version}"
)
EOF
# gofmt -s -w topology/default_versions.go
