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

ROOT=/data/agents/clawd

mkdir -p /data/ssh /data/.cache/pip /data/.cache/npm /data/.local
mkdir -p "$ROOT/bin" "$ROOT/src" "$ROOT/tmp" "$ROOT/logs" "$ROOT/notes" "$ROOT/tools"

for keytype in rsa ecdsa ed25519; do
    if [ ! -f "/data/ssh/ssh_host_${keytype}_key" ]; then
        echo "Generating persistent host ${keytype} key..."
        ssh-keygen -q -f "/data/ssh/ssh_host_${keytype}_key" -N '' -t "$keytype"
    fi
done
chmod 600 /data/ssh/ssh_host_*_key

if [ -f /data/.gitconfig ]; then
    ln -sf /data/.gitconfig "$HOME/.gitconfig"
fi

cat > "$ROOT/README.md" <<'EOF'
# ClawdBox Agent Workspace

Durable agent workspace for OpenClaw work that should survive pod restarts.

- `bin/` helper commands
- `src/` source checkouts and experiments
- `tmp/` scratch files
- `logs/` process logs
- `notes/` operator notes
- `tools/` persistent tool installs
EOF

for script in start-clawdbox-node status-clawdbox-node stop-clawdbox-node; do
    cp "/usr/local/bin/${script}" "$ROOT/bin/${script}"
done

export PATH="$ROOT/bin:/usr/local/bin:$PATH"

start-clawdbox-node || {
    echo "ClawdBox-CLI node host did not start; SSH will remain available." >&2
}

exec /usr/sbin/sshd -D -e -f /etc/ssh/sshd_config
