#!/bin/sh
# Lambda custom-runtime bootstrap — pulls the aarch64-musl Rust binary
# on cold-start, fetches the peer-seed from SSM Parameter Store, then
# runs the Lambda runtime API loop.
#
# Lambda cold start with Rust: ~50ms typical.
set -eu

# 1. Resolve seed from SSM (one-shot per cold start; cached in /tmp by Lambda)
if [ -z "${PEER_SEED:-}" ]; then
    PEER_SEED=$(aws ssm get-parameter --name "$PEER_SEED_SSM_PATH" \
        --with-decryption --query Parameter.Value --output text)
    export PEER_SEED
fi

mkdir -p /tmp/arqera
umask 077
printf '%s' "$PEER_SEED" > /tmp/arqera/peer.key

# 2. Twin binary lives at /opt/twin (Lambda Layer) — see template.yaml for
#    the layer attachment; if absent, fetch from GitHub Release on cold start.
TWIN_BIN=/opt/twin
if [ ! -x "$TWIN_BIN" ]; then
    BASE="https://github.com/Arqera-IO/ara-protocol/releases/download/v0.3.0"
    curl -fsSL "$BASE/twin-aarch64-unknown-linux-musl.tar.xz" -o /tmp/twin.tar.xz
    tar -xJf /tmp/twin.tar.xz -C /tmp --strip-components=1
    TWIN_BIN=/tmp/twin
fi

export HOME=/tmp/arqera

# 3. Lambda runtime API loop — each invocation is one substrate handoff.
while true; do
    HEADERS=$(mktemp)
    EVENT=$(curl -sS -LD "$HEADERS" \
        "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next")
    REQUEST_ID=$(grep -i 'Lambda-Runtime-Aws-Request-Id' "$HEADERS" | sed 's/.*: //' | tr -d '\r')

    # The event payload IS the handoff. Pass to twin for processing.
    RESPONSE=$(echo "$EVENT" | "$TWIN_BIN" handoff receive --stdin 2>/dev/null || echo "{}")

    curl -sS -X POST -d "$RESPONSE" \
        "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/${REQUEST_ID}/response" \
        >/dev/null
done
