#!/bin/sh

# Generator for .devcontainer/Dockerfile
# Combines the root /Dockerfile (with some COPY lines removed) and
# the dev-only stage in .devcontainer/resources/devcontainer-Dockerfile.
# Run this script after modifying the resource Dockerfile to refresh
# the final .devcontainer/Dockerfile used by the devcontainer.

# Make a copy of the original Dockerfile to the .devcontainer folder
# but remove the COPY . ${INSTALL_DIR}/ command from it. This avoids
# overwriting /app (which uses symlinks to the workspace) and preserves
# debugging capabilities inside the devcontainer.

SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
DEVCONTAINER_DIR="${SCRIPT_DIR%/scripts}"
ROOT_DIR="${DEVCONTAINER_DIR%/.devcontainer}"

OUT_FILE="${DEVCONTAINER_DIR}/Dockerfile"

echo "# DO NOT MODIFY THIS FILE DIRECTLY. IT IS AUTO-GENERATED BY .devcontainer/scripts/generate-dockerfile.sh" > "$OUT_FILE"
echo "" >> "$OUT_FILE"
echo "# ---/Dockerfile---" >> "$OUT_FILE"

sed '/${INSTALL_DIR}/d' "${ROOT_DIR}/Dockerfile" >> "$OUT_FILE"

# sed the line https://github.com/foreign-sub/aiofreepybox.git \\ to remove trailing backslash
sed -i '/aiofreepybox.git/ s/ \\$//' "$OUT_FILE"

# don't cat the file, just copy it in because it doesn't exist at build time
sed -i 's|^ RUN cat ${INSTALL_DIR}/install/freebox_certificate.pem >> /opt/venv/lib/python3.12/site-packages/aiofreepybox/freebox_certificates.pem$| COPY install/freebox_certificate.pem /opt/venv/lib/python3.12/site-packages/aiofreepybox/freebox_certificates.pem |' "$OUT_FILE"

echo "" >> "$OUT_FILE"
echo "# ---/resources/devcontainer-Dockerfile---" >> "$OUT_FILE"
echo "" >> "$OUT_FILE"

cat "${DEVCONTAINER_DIR}/resources/devcontainer-Dockerfile" >> "$OUT_FILE"

echo "Generated $OUT_FILE using root dir $ROOT_DIR" >&2
