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

set -euo pipefail

HARBOR_REGISTRY="registry.squirro.com"
HARBOR_PROJECT="squirro-cli"
DOCKER_IMAGE_NAME="squirro-cli"
DOCKER_IMAGE_TAG="latest"
DOCKER_IMAGE="${HARBOR_REGISTRY}/${HARBOR_PROJECT}/${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_TAG}"
SCRIPT_URL="https://mirror.squirro.net/extras/squirro-cli-docker.sh"

# Handle built-in wrapper commands before passing args to Docker
if [ "${1:-}" = "self" ] && [ "${2:-}" = "update" ]; then
    echo "Updating squirro wrapper script from ${SCRIPT_URL}..."
    TEMP_FILE=$(mktemp)
    curl -fsSL "$SCRIPT_URL" -o "$TEMP_FILE"
    sudo mv "$TEMP_FILE" "$(realpath "$0")"
    sudo chmod +x "$(realpath "$0")"
    echo "Updating squirro-cli Docker image..."
    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" "$@"
