#!/bin/bash

MODE="$1" # 'rw' or 'readonly'
CONTAINER="$SSH_ORIGINAL_COMMAND"
IMAGE="analytics-backend-workspace" # change to match your setup
TMUX_SESSION="analytics-backend"
DEV_USER="devuser"
VIEW_USER="viewer"

# Function to start the container if not running
start_container_if_needed() {
  if ! podman container exists "$CONTAINER"; then
    echo "🚀 Creating container $CONTAINER..."
    podman run -dit \
      --userns=keep-id \
      --name "$CONTAINER" \
      --user "$DEV_USER" \
      --hostname "$CONTAINER" \
      --label auto-cleanup=true \
      -v "${XDG_RUNTIME_DIR}"/podman/podman.sock:/run/podman/podman.sock \
      "$IMAGE" sh -c "tmux has-session -t $TMUX_SESSION 2>/dev/null || tmux new-session -s $TMUX_SESSION"
  elif ! podman inspect -f '{{.State.Running}}' "$CONTAINER" | grep -q true; then
    echo "⚡ Starting existing container $CONTAINER..."
    podman start "$CONTAINER"
  fi
}

# After devuser exits...
check_devuser_attached() {
  # Get list of clients
  client_users=$(podman exec "$CONTAINER" tmux list-clients -t "$TMUX_SESSION" -F "#{client_user}" 2>/dev/null)

  if echo "$client_users" | grep -q "$USER"; then
    echo "💡 devuser still attached — container stays running"
    return 0
  else
    echo "⚠️  devuser has exited — stopping container"
    podman stop "$CONTAINER"
    return 1
  fi
}

# === Main ===

case "$MODE" in
rw)
  start_container_if_needed

  # Run tmux session inside the container
  if ! podman exec -it --user "$USER" "$CONTAINER" tmux has-session -t "$TMUX_SESSION" 2>/dev/null; then
    if ! podman exec -it --user "$USER" "$CONTAINER" tmux new-session -s "$TMUX_SESSION"; then
      echo "❌ Could not attach to tmux session. Please contact admin or try again later."
      podman logs "$CONTAINER"
      exit 1
    fi
  else
    if ! podman exec -it --user "$USER" "$CONTAINER" tmux attach -t "$TMUX_SESSION"; then
      echo "❌ Could not attach to tmux session. Please contact admin or try again later."
      podman logs "$CONTAINER"
      exit 1
    fi
  fi

  check_devuser_attached
  exit 0
  ;;
ro)
  if podman container exists "$CONTAINER" && podman inspect -f '{{.State.Running}}' "$CONTAINER" | grep -q true; then
    if ! podman exec -it --user "$VIEW_USER" "$CONTAINER" tmux attach -r -t "$TMUX_SESSION"; then
      echo "❌ Could not attach to tmux session. Please contact admin or try again later."
      podman logs "$CONTAINER"
      exit 1
    fi
    exit 0
  else
    echo "❌ Container $CONTAINER does not exist."
    exit 1
  fi
  ;;
*)
  echo "❌ Invalid access mode: $MODE"
  exit 1
  ;;
esac