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

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

cd "${ROOT_DIR}"

mkdir -p "${CACHE_DIR}"

if [[ ! -f /etc/ros/rosdep/sources.list.d/20-default.list ]]; then
    sudo rosdep init
fi

rosdep update
export DEBIAN_FRONTEND=noninteractive
sudo apt-get update -qq

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

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}"

{
    echo "# Generated by .devcontainer/refresh-rosdep-cache.sh"
    echo "# apt packages resolved from rosdep keys in src"
    cat "${tmp_packages}"
} > "${APT_LIST_FILE}"

echo "Updated ${APT_LIST_FILE}"