#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ROSDEP_APT_LIST_FILE="${ROOT_DIR}/.devcontainer/${ROS_DISTRO}/rosdep-apt-packages.txt"


if [[ -f /usr/local/share/host-certificates/AMD_CA.crt ]]; then
	sudo cp /usr/local/share/host-certificates/AMD_CA.crt /usr/local/share/ca-certificates/
	sudo update-ca-certificates
fi

if [[ ! -f "${ROSDEP_APT_LIST_FILE}" ]]; then
	echo "Missing ${ROSDEP_APT_LIST_FILE}."
	echo "Run .devcontainer/refresh-rosdep-cache.sh and rebuild the devcontainer."
	exit 1
fi

tmp_packages="$(mktemp)"
cleanup() {
	rm -f "${tmp_packages}"
}
trap cleanup EXIT

export DEBIAN_FRONTEND=noninteractive
sudo apt-get update -qq

rosdep keys --from-paths src --ignore-src 2>/dev/null \
	| xargs -r rosdep resolve --rosdistro "${ROS_DISTRO}" --filter-for-installers=apt 2>/dev/null \
	| sed -e '/^#/d' -e '/^$/d' \
	| LC_ALL=C sort -u > "${tmp_packages}"

if ! diff -u <(grep -Ev '^\s*($|#)' "${ROSDEP_APT_LIST_FILE}") "${tmp_packages}" >/dev/null; then
	echo "rosdep-resolved apt packages differ from ${ROSDEP_APT_LIST_FILE}."
	echo "Run .devcontainer/refresh-rosdep-cache.sh and rebuild the devcontainer."
	exit 1
fi

echo "rosdep apt cache is current; no post-create package installation needed."

if compgen -G "${ROOT_DIR}/src/robotnik/robotnik_simulation/debs/ros-jazzy-*.deb" > /dev/null; then
	sudo apt-get install -y "${ROOT_DIR}"/src/robotnik/robotnik_simulation/debs/ros-jazzy-*.deb
fi