#!/bin/bash
# Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
# SPDX-License-Identifier: MIT

# CK Shell - Open interactive shell in Docker container

set -e
set -o pipefail

# Find script directory and load common utilities
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/common.sh"

# Initialize configuration
PROJECT_ROOT=$(get_project_root "${SCRIPT_DIR}")
CONTAINER_NAME=$(get_container_name "${PROJECT_ROOT}")

# Help message
show_help() {
    cat << EOF
CK Shell - Open interactive shell in Docker container

Usage: ck-shell [options] [container_name]

Options:
  -h, --help              Show this help message
  --name <name>           Specify container name
  -c <command>            Execute command instead of interactive shell

Arguments:
  container_name          Optional container name (default: ck_<username>_<branch>)

Environment:
  CK_CONTAINER_NAME - Override default container name

Examples:
  ck-shell                           # Open interactive shell
  ck-shell my_container              # Open shell in specific container
  ck-shell -c "rocm-smi"             # Execute single command
  ck-shell -c "cd build && ls bin"   # Execute command in build directory

EOF
}

# Parse arguments
command=""

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        --name)
            CONTAINER_NAME="$2"
            shift 2
            ;;
        -c)
            command="$2"
            shift 2
            ;;
        *)
            CONTAINER_NAME="$1"
            shift
            ;;
    esac
done

# Ensure container is running
if ! container_is_running "${CONTAINER_NAME}"; then
    echo "Container '${CONTAINER_NAME}' not running. Starting..."
    "${SCRIPT_DIR}/ck-start" "${CONTAINER_NAME}"
    echo ""
fi

# Execute command or open shell
if [ -n "$command" ]; then
    echo "Executing: ${command}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    docker exec "${CONTAINER_NAME}" bash -c "${command}"
else
    echo "Opening shell in '${CONTAINER_NAME}' (type 'exit' to leave)..."
    docker exec -it "${CONTAINER_NAME}" bash
fi
