#!/bin/bash
set -euo pipefail

# Prevent apt/dpkg from blocking on interactive prompts (e.g. tzdata).
export DEBIAN_FRONTEND=noninteractive

echo "=== Installing lace ==="

# Use apt-cacher-ng proxy on Docker host to avoid hammering upstream mirrors
# when many containers install packages simultaneously.
# Each harbor task gets its own Docker network, so detect the gateway dynamically.
# `ip` may not be installed in minimal containers, so parse /proc/net/route directly.
GW_HEX=$(awk '$2 == "00000000" {print $3; exit}' /proc/net/route 2>/dev/null)
if [ -n "$GW_HEX" ]; then
    DOCKER_GW=$(printf "%d.%d.%d.%d" "0x${GW_HEX:6:2}" "0x${GW_HEX:4:2}" "0x${GW_HEX:2:2}" "0x${GW_HEX:0:2}")
    echo "Acquire::http::Proxy \"http://${DOCKER_GW}:3142\";" > /etc/apt/apt.conf.d/01proxy
fi

# Most terminal-bench containers already have Node.js.
# Install from pre-bundled binary tarball if missing (< 1s, no apt/network).
if ! command -v node &>/dev/null; then
    echo "Node.js not found, installing from tarball..."
    tar -xzf /installed-agent/node-v22-linux-x64.tar.gz -C /usr/local --strip-components=1
fi

echo "Node.js: $(node --version)"

# Install ripgrep (lace uses it for search)
if ! command -v rg &>/dev/null; then
    apt-get update -qq 2>/dev/null || true
    apt-get install -y -qq ripgrep 2>/dev/null || echo "ripgrep install failed (non-fatal)"
fi

# Copy pre-built lace bundle from /installed-agent/lace to /opt/lace.
# The bundle was created by deploy-lace.sh and already has node_modules.
cp -r /installed-agent/lace /opt/lace

# Make the harness executable
chmod +x /opt/lace/tools/lace-harness.mjs

# Configure git for benchmark tasks (git may not be installed in all containers)
if command -v git &>/dev/null; then
    git config --global safe.directory '*'
fi

echo "=== lace installed ==="
echo "Harness: /opt/lace/tools/lace-harness.mjs"
