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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib.sh
source "${SCRIPT_DIR}/lib.sh"

# Create an immutable-ish code snapshot under:
#   ${SHARED_ROOT}/common/code/verl/<code_id>
#
# By default, code_id is the git commit hash of /workspace/verl (mounted from ../verl).
#
# This enables job-level multi-version coexistence via runtime_env PYTHONPATH injection.

CODE_ID="${CODE_ID:-}"

if [[ -z "${CODE_ID}" ]]; then
  CODE_ID="$(dexec "${HEAD_CONTAINER}" bash -lc "git config --global --add safe.directory /workspace/verl >/dev/null 2>&1 || true; git -C /workspace/verl rev-parse HEAD")"
fi

DEST_DIR="${SHARED_ROOT}/common/code/verl/${CODE_ID}"

echo "[head] snapshot verl repo -> ${DEST_DIR}"

if dexec "${HEAD_CONTAINER}" bash -lc "test -d '${DEST_DIR}'"; then
  echo "[head] code_snapshot_exists: skip"
  exit 0
fi

dexec "${HEAD_CONTAINER}" bash -lc "mkdir -p '${DEST_DIR}'"

# Copy code (no .git needed for runtime)
if dexec "${HEAD_CONTAINER}" bash -lc "command -v rsync >/dev/null 2>&1"; then
  dexec "${HEAD_CONTAINER}" bash -lc "rsync -a --delete --exclude='.git' /workspace/verl/ '${DEST_DIR}/'"
else
  dexec "${HEAD_CONTAINER}" bash -lc "tar -C /workspace/verl -cf - --exclude='.git' . | tar -C '${DEST_DIR}' -xf -"
fi

# Add a tiny marker module for multi-version validation in Ray job logs.
dexec "${HEAD_CONTAINER}" bash -lc "printf \"%s\\n\" \"MARKER = '${CODE_ID}'\" > '${DEST_DIR}/mvp_marker.py'"

echo "[head] code_snapshot_ok: ${CODE_ID}"
