#!/usr/bin/env bash
# Wrapper script to run squirro-cli via Docker.
#
# Usage:
#   squirro [options...]
#
# Install (add to PATH as "squirro"):
#   curl -fsSL <mirror-url>/squirro-cli-docker.sh -o /usr/local/bin/squirro
#   chmod +x /usr/local/bin/squirro

set -euo pipefail

HARBOR_REGISTRY="registry.squirro.com"
DOCKER_IMAGE_NAME="squirro-cli"
DOCKER_IMAGE_TAG="latest"
DOCKER_IMAGE="${HARBOR_REGISTRY}/${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_TAG}"

# Handle built-in wrapper commands before passing args to Docker
if [ "${1:-}" = "self" ] && [ "${2:-}" = "update" ]; then
    docker login "$HARBOR_REGISTRY"
    exec docker pull "$DOCKER_IMAGE"
fi

# Detect whether we have a TTY so interactive commands (e.g. squirro chat) work
if [ -t 0 ] && [ -t 1 ]; then
    TTY_FLAGS=(-it)
else
    TTY_FLAGS=(-i)
fi

exec docker run --rm \
    "${TTY_FLAGS[@]}" \
    --user "$UID:$(id -g)" \
    --env "HOME=$HOME" \
    -v "${HOME}/.squirro:${HOME}/.squirro" \
    -v "$(pwd):$(pwd)" \
    -w "$(pwd)" \
    "$DOCKER_IMAGE" "$@"
