#!/bin/sh
set -eu

if [ "$(id -u)" -eq 0 ]; then
  echo "Run as a non-root user with access to the local Docker Engine, not with sudo." >&2
  exit 1
fi

cd "$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
umask 077

for tool in bao docker timeout; do
  if ! command -v "$tool" >/dev/null 2>&1; then
    echo "Missing required command: $tool" >&2
    exit 1
  fi
done

docker compose version >/dev/null
mkdir -p .runtime
chmod 700 .runtime
for file in tls/ca.pem .runtime/role-id .runtime/secret-id; do
  if [ ! -s "$file" ]; then
    echo "Required input is missing or empty: $file" >&2
    exit 1
  fi
done
chmod 600 .runtime/role-id .runtime/secret-id

export APP_UID="$(id -u)"
export APP_GID="$(id -g)"
unset BAO_TOKEN BAO_SKIP_VERIFY BAO_WRAP_TTL

timeout --kill-after=5s 60s bao agent -config=agent.hcl
test -s .runtime/app.json
docker compose config -q
docker compose up --build -d --force-recreate app
