#!/bin/bash
case $1 in "-a") PROMPT="Goto:"; MODE="go" ;; "-R") PROMPT="Bring:"; MODE="bring" ;; esac

if [ -n "$2" ]; then
    WINDOW="$2"
else
    WINDOW=$(paste \
           <(xdotool search .) \
           <(xdotool search . get_desktop_for_window %@ 2> /dev/null) \
           <(xdotool search . getwindowname %@) |\
        awk '{FS="\t"; if($2 != -1) printf "%10d [%d] %s\n",$1,$2+1,$3}' |\
        vmenu --no-refocus -p $PROMPT |\
        sed 's/^ *//g' |\
        cut -d ' ' -f 1)
fi

if [ -n "$WINDOW" ]; then
    if [ bring = $MODE ]; then
        if DESK=$(xdotool get_desktop 2> /dev/null); then
            xdotool set_desktop_for_window "$WINDOW" $DESK
            sleep 0.005 # wait for wm to notice
        fi
    fi
    xdotool windowmap "$WINDOW" windowactivate "$WINDOW" windowfocus "$WINDOW" windowraise "$WINDOW"
fi
