#!/usr/bin/env bash
# Run Kamal without installing Ruby — via its official container image.
#
#   bin/kamal setup  -d dev
#   bin/kamal deploy -d dev
#   bin/kamal app logs -d dev -f
#
# Requires: Docker, an SSH agent (or ~/.ssh keys) that can reach the target, and
# the secret env vars listed in .kamal/secrets exported in your shell.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
KAMAL_IMAGE="${KAMAL_IMAGE:-ghcr.io/basecamp/kamal:latest}"

# Stamp the hub binary version from git for the image build.
export HUB_VERSION="${HUB_VERSION:-$(git -C "$REPO_ROOT" describe --tags --always --dirty 2>/dev/null || echo dev)}"

# Load repo-root .env if present. Kamal itself does not auto-load .env in
# this container-wrapped setup (verified: a from-scratch `kamal config -d
# production` with zero forwarded vars falls back to deploy.production.yml's
# own placeholder host) — without this, every var in the loop below had to
# be exported by hand before every single invocation.
if [[ -f "${REPO_ROOT}/.env" ]]; then
  set -a
  # shellcheck disable=SC1091
  source "${REPO_ROOT}/.env"
  set +a
fi

# Forward every var .kamal/secrets pulls from the environment.
ENV_ARGS=()
for var in KAMAL_REGISTRY_PASSWORD MAYLYN_SERVE_TOKEN POSTGRES_PASSWORD \
           SECRETS_COOKIE SECRETS_CIPHER COURIER_SMTP_CONNECTION_URI \
           MAYLYN_CLOUDFLARE_TUNNEL_TOKEN MAYLYN_GITHUB_TOKEN \
           HUB_VERSION DEV_HOST DEV_SSH_USER DEV_HUB_URL \
           PROD_HOST PROD_SSH_USER PROD_HUB_HOST WEBSITE_HOST; do
  if [[ -n "${!var:-}" ]]; then ENV_ARGS+=(-e "$var"); fi
done

SSH_ARGS=()
if [[ -n "${SSH_AUTH_SOCK:-}" && -S "${SSH_AUTH_SOCK}" ]]; then
  SSH_ARGS+=(-v "${SSH_AUTH_SOCK}:/ssh-agent" -e "SSH_AUTH_SOCK=/ssh-agent")
elif [[ -d "${HOME}/.ssh" ]]; then
  SSH_ARGS+=(-v "${HOME}/.ssh:/root/.ssh:ro")
fi

# -it needs a real terminal on stdin; a script or CI runner invoking this
# non-interactively gets "cannot attach stdin to a TTY-enabled container
# because stdin is not a terminal" and the deploy never starts. -i alone
# still forwards stdin (kamal doesn't need a tty to run) and works in both
# contexts, so detect rather than always assume an interactive shell.
DOCKER_TTY_FLAG="-i"
if [[ -t 0 ]]; then
  DOCKER_TTY_FLAG="-it"
fi

exec docker run --rm "${DOCKER_TTY_FLAG}" \
  -v "${REPO_ROOT}:/workdir" \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -w /workdir \
  "${SSH_ARGS[@]}" \
  "${ENV_ARGS[@]}" \
  "${KAMAL_IMAGE}" "$@"
