#!/bin/bash
# Runs in the target root during `rpm-ostree compose image` (edition 2024
# finalize.d hook). rpm-ostree relocates RPM content under /opt to
# /usr/lib/opt. With `opt-usrlocal: root` /opt is a plain directory in the
# image and nothing links it back, so link each vendor directory. Images on the
# default (/opt -> /var/opt, linked by tmpfiles.d) are left alone.
set -euo pipefail

root="${PWD}"

[[ -d "${root}/usr/lib/opt" ]] || exit 0
if [[ -L "${root}/opt" || ! -d "${root}/opt" ]]; then
  exit 0
fi

for dir in "${root}"/usr/lib/opt/*; do
  name="$(basename "${dir}")"
  ln -sfn "../usr/lib/opt/${name}" "${root}/opt/${name}"
  echo "Linked /opt/${name} -> /usr/lib/opt/${name}"
done
