#!/usr/bin/env bash

# Copyright (C) 2008-2013 Bob Hepple
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# http://bhepple.freeshell.org

check_and_process_opts() {
    local TEMP

    ARGS="
ARGP_DELETE=quiet
ARGP_VERSION=$VERSION
ARGP_PROG=$PROG
##############################################################   
#OPTIONS:
#name=default sname arg       type range   description
##############################################################   
ALL=''        a     ''        b    ''      Move all windows even if on another console or desktop.
ZERO=''       z     ''        b    ''      Also move windows to origin
##############################################################   
ARGP_ARGS=[--] $ARGUMENTS
ARGP_SHORT=$SHORT_DESC
ARGP_USAGE=$USAGE"

    exec 4>&1
    eval $(echo "$ARGS" | argp.sh "$@" 3>&1 1>&4 || echo exit $? )
    exec 4>&-

    NEW_ARGS=( "$@" )
    return 0
}

PROG=$(basename $0)
VERSION="1.2"
SHORT_DESC="Move windows to new workspace. "
TITLE_FILTER=""
HORIZONTAL=""
ALL=

USAGE="Uses wmctrl(1). \
If title filter (regex) is given then \
only those windows whose title matches will be moved."

VERBOSE=""
ARGUMENTS="new-desktop [ title filter ]"

NEW_ARGS=( )
check_and_process_opts "$@" && set -- "${NEW_ARGS[@]}"

NEW_DESKTOP=$1; shift
TITLE_FILTER="$@"

type wmctrl &> /dev/null || {
    echo "$PROG: wmctrl is not installed" >&2
    exit 1
}

source xwin-utils

set -- `xwin-list-desktops | awk '/\*/ { print $1 " " $4; } END {print $1}'`
CURRENT_DESKTOP=$1
LAST_DESKTOP=$3

#wmctrl uses base 0:
[[ "$NEW_DESKTOP" && "$NEW_DESKTOP" =~ [0-9]+ && "$NEW_DESKTOP" -gt 0 &&
        "$((--NEW_DESKTOP))" -le "$LAST_DESKTOP" ]] || {
    echo "$PROG: you need to give the new desktop number (1-$((LAST_DESKTOP + 1)))" >&2
    exit 1
}

CONS_LIST=
LIMIT_TO_CONS=
[[ "$ALL" ]] || {
    CONS_LIST=( $( xwin-list-consoles) )
    if (( ${#CONS_LIST[@]} > 1 )); then
        LIMIT_TO_CONS=$( xwin-get-con 0 0)
    fi
}

# gather, filter and sort window data:
# wmctrl format is 
# id desktop x y width height client title
xwin-list-windows | \
    while read ID DESKTOP X Y WIDTH HEIGHT CLASS CLIENT TITLE; do
        [[ "$VERBOSE" ]] && echo "considering $ID $DESKTOP $X $Y $CLASS"
        if [[ "$LIMIT_TO_CONS" ]]; then
            WIN_CONS=$(xwin-get-con $(( X + WIDTH / 2 )) $(( Y + HEIGHT / 2)) )
            [[ $WIN_CONS == $LIMIT_TO_CONS ]] || continue
        fi
        # [ $DESKTOP -lt 0 ] && continue # ignore sticky windows
        if [[ "$ALL" || "$DESKTOP" == "$CURRENT_DESKTOP" ]]; then
            [ "$TITLE_FILTER" ] && { 
                [[ "$TITLE" =~ "$TITLE_FILTER" ]] || continue
            }

            [ "$VERBOSE" ] && echo "Moving \"$TITLE\""
            xwin-move-to-desktop $ID $NEW_DESKTOP
            [[ "$ZERO" ]] && xwin-move-resize $ID 0,0,0,-1,-1
        fi
    done
xwin-switch-desktop $NEW_DESKTOP
