#!/bin/bash

# Automatically sets up your devbox environment whenever you cd into this
# directory via our direnv integration:

eval "$(devbox generate direnv --print-envrc)"
dotenv_if_exists

# Activate the local .venv Python environment
if [ -d .venv ]; then
  export VIRTUAL_ENV="$PWD/.venv"
  PATH_add "$VIRTUAL_ENV/bin"
fi

# Setup SSH tunnel to Exasol database (must run AFTER dotenv loads DOCKER_HOST)
# Only start tunnel if DOCKER_HOST points to a remote host via SSH
if [ -n "$DOCKER_HOST" ] && [[ "$DOCKER_HOST" == ssh://* ]]; then
  DB_SSH_HOST=$(echo $DOCKER_HOST | sed 's|ssh://[^@]*@||')
  DB_PORT=${DB_PORT:-8563}
  TUNNEL_PID=$(pgrep -f "ssh.*${DB_PORT}:localhost:${DB_PORT}.*${DB_SSH_HOST}")
  if [ -z "$TUNNEL_PID" ]; then
    echo "Starting SSH tunnel to Exasol database (localhost:${DB_PORT} -> ${DB_SSH_HOST}:${DB_PORT})..."
    ssh -f -N -L ${DB_PORT}:localhost:${DB_PORT} root@${DB_SSH_HOST} 2>/dev/null
    if [ $? -eq 0 ]; then
      echo 'SSH tunnel established successfully'
    else
      echo 'Warning: Failed to establish SSH tunnel'
    fi
  else
    echo "SSH tunnel already running (PID: $TUNNEL_PID)"
  fi
fi

# Create wrapper script for nox to use .venv if available
mkdir -p .devbox/bin
cat > .devbox/bin/nox << 'EOF'
#!/bin/bash
# Use nox from .venv if available, otherwise fall back to uv tool run
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")"
if [ -f "$PROJECT_ROOT/.venv/bin/nox" ]; then
  exec "$PROJECT_ROOT/.venv/bin/nox" "$@"
else
  exec uv tool run nox "$@"
fi
EOF
chmod +x .devbox/bin/nox

# Add .devbox/bin to PATH (must be after devbox generate)
PATH_add .devbox/bin

# Configure Docker to connect via SSH
if [ -n "$DOCKER_SSH_HOST" ]; then
  export DOCKER_HOST="ssh://${DOCKER_SSH_HOST}"
  export DOCKER_BUILDKIT=1
  export DOCKER_API_VERSION=1.41  # Compatible with Docker 20.10.x
fi

# check out https://www.jetify.com/docs/devbox/ide_configuration/direnv/
# for more details
