#!/bin/bash
# Script to run logcli in Docker container
# Usage: ./run_logcli.sh [arguments]
# Example: ./run_logcli.sh logs download --cluster xxx --vendor aws --region us-west-2

set -e

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Docker image name
IMAGE_NAME="observability-logcli"

# Local output directory (will be created if not exists)
LOCAL_DIR="${SCRIPT_DIR}/local"

# Create local directory if it doesn't exist
mkdir -p "${LOCAL_DIR}"

# Check if image exists, if not build it
if ! docker image inspect "${IMAGE_NAME}" &> /dev/null; then
    echo "Docker image '${IMAGE_NAME}' not found. Building..."
    docker build -t "${IMAGE_NAME}" "${SCRIPT_DIR}"
fi

# Run the docker container with:
# - Mount local directory for output
# - Mount auth directory for credentials (if exists)
# - Pass all script arguments to the container
MOUNT_ARGS="-v ${LOCAL_DIR}:/app/local"

# Environment variables to pass to container
ENV_ARGS=""

# Pass GITHUB_TOKEN if set
if [ -n "${GITHUB_TOKEN}" ]; then
    ENV_ARGS="${ENV_ARGS} -e GITHUB_TOKEN=${GITHUB_TOKEN}"
fi

# Mount ~/.observability directory for cached credentials
OBSERVABILITY_DIR="${HOME}/.observability"
if [ -d "${OBSERVABILITY_DIR}" ]; then
    MOUNT_ARGS="${MOUNT_ARGS} -v ${OBSERVABILITY_DIR}:/root/.observability"
fi

# Mount auth directory if it exists
AUTH_DIR="${SCRIPT_DIR}/auth"
if [ -d "${AUTH_DIR}" ]; then
    MOUNT_ARGS="${MOUNT_ARGS} -v ${AUTH_DIR}:/app/auth"
fi

# Mount AWS credentials if they exist
if [ -d "${HOME}/.aws" ]; then
    MOUNT_ARGS="${MOUNT_ARGS} -v ${HOME}/.aws:/root/.aws:ro"
fi

# Mount GCP credentials if they exist
if [ -d "${HOME}/.config/gcloud" ]; then
    MOUNT_ARGS="${MOUNT_ARGS} -v ${HOME}/.config/gcloud:/root/.config/gcloud:ro"
fi

# Run docker with all arguments passed through
docker run --rm ${ENV_ARGS} ${MOUNT_ARGS} "${IMAGE_NAME}" "$@"
