diff --git a/ssh_router.sh b/ssh_router.sh new file mode 100644 index 0000000..338f20d --- /dev/null +++ b/ssh_router.sh @@ -0,0 +1,67 @@ +#!/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 \ + --name "$CONTAINER" \ + --user "$DEV_USER" \ + --hostname devbox \ + --label auto-cleanup=true \ + "$IMAGE" bash + 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 + podman exec -it --user "$USER" "$CONTAINER" tmux new-session -s "$TMUX_SESSION" + else + podman exec -it --user "$USER" "$CONTAINER" tmux attach -t "$TMUX_SESSION" + fi + + check_devuser_attached + ;; +ro) + if ! podman container exists "$CONTAINER" || ! podman inspect -f '{{.State.Running}}' "$CONTAINER" | grep -q true; then + echo "❌ Container '$CONTAINER' not running." + exit 1 + fi + exec podman exec -it --user "$VIEW_USER" "$CONTAINER" tmux attach -r -t "$TMUX_SESSION" + ;; +*) + echo "❌ Invalid access mode: $MODE" + exit 1 + ;; +esac