#!/bin/sh
# Serves the run's proxy socket on loopback, where HTTPS_PROXY points, and with BOTBOX_CREDENTIALS
# the credential proxy's on 41894, then runs the command.
# Sharing the proxy's uid would let the agent signal it and read its /proc.
if [ "$(id -u)" = "$(awk '/^Uid:/ {print $2}' /proc/1/status)" ]; then
    echo "botbox-relay: the agent runs as the proxy's uid $(id -u); use another" >&2
    exit 125
fi
if [ "$(id -u)" = 101 ]; then
    echo "botbox-relay: the agent runs as the credential proxy's uid 101; use another" >&2
    exit 125
fi
# OpenShift's arbitrary-uid pattern: name a uid the image has no passwd entry for.
if ! whoami >/dev/null 2>&1 && [ -w /etc/passwd ]; then
    echo "user:x:$(id -u):$(id -g):user:/home/user:/bin/sh" >>/etc/passwd
fi
# The agent's staged files: a tar.gz of this many bytes at the head of stdin. GNU head reads
# no further, so the rest of stdin is the command's.
if [ -n "${BOTBOX_HOME_BYTES:-}" ]; then
    if ! head -c "$BOTBOX_HOME_BYTES" | tar -xz -m -C "$HOME"; then
        echo "botbox-relay: could not write the agent's files into $HOME" >&2
        exit 1
    fi
    unset BOTBOX_HOME_BYTES
fi
# The subshell orphans socat, so the command's shell never waits on it.
(socat TCP-LISTEN:41893,bind=127.0.0.1,fork,reuseaddr UNIX-CONNECT:/run/botbox/proxy.sock &)
if [ -n "${BOTBOX_CREDENTIALS:-}" ]; then
    if [ ! -S /run/botbox/credentials.sock ]; then
        echo "botbox-relay: the run asked for credential injection, but /run/botbox/credentials.sock is missing" >&2
        exit 1
    fi
    (socat TCP-LISTEN:41894,bind=127.0.0.1,fork,reuseaddr UNIX-CONNECT:/run/botbox/credentials.sock &)
fi
tries=0
until grep -q ':A3A5 00000000:0000 0A' /proc/net/tcp; do
    tries=$((tries + 1))
    if [ "$tries" -gt 250 ]; then
        echo "botbox-relay: nothing listening on 127.0.0.1:41893" >&2
        exit 1
    fi
    sleep 0.02
done
if [ -n "${BOTBOX_CREDENTIALS:-}" ]; then
    tries=0
    until grep -q ':A3A6 00000000:0000 0A' /proc/net/tcp; do
        tries=$((tries + 1))
        if [ "$tries" -gt 250 ]; then
            echo "botbox-relay: nothing listening on 127.0.0.1:41894" >&2
            exit 1
        fi
        sleep 0.02
    done
fi
exec "$@"
