#!/bin/bash

# With no parameters, move the last window that was opened
if [ $# -eq 0 ]; then
    winID=$(wmctrl -l |cut -f1 -d' ' | tail -n1)
    wmctrl -i -r $winID -e"0,0,0,-1,-1"

# -h, --help: show the help text
elif [[ "$1" = '-h' ]] || [[ "$1" = '--help' ]]; then
    echo 'Usage: gather_windows.sh [option]'
    echo 'With no options    : move the last opened window to the top left of the screen'
    echo '-1, -p, --previous : move the previously opened window to the top left of the screen'
    echo '-i, --inkscape     : move all the Inkscape windows to the top left of the screen'
    echo '-a, --all          : move all the windows from all applications to the top left of the screen'
    echo '-h, --help         : show this help text'
    echo 'With any other option, try to find windows that match the string provided as part of their WM_CLASS property, and move them to the top left.'
    echo
    echo 'Note: the -1 option lets you open a terminal to run this script *after* your window has gone missing'

# -1, -p, --previous: move the previously opened window
elif [[ "$1" = '-1' ]] || [[ "$1" = '-p' ]] || [[ "$1" = '--previous' ]]; then
    winID=$(wmctrl -l |cut -f1 -d' ' | tail -n2 | head -n1)
    wmctrl -i -r $winID -e"0,0,0,-1,-1"


# -a, --all: move all windows
elif [[ "$1" = '-a' ]] || [[ "$1" = '--all' ]]; then
    count=0

    for winID in $(wmctrl -l |cut -f1 -d' ');
    do
        x=$(( $count * 15 ))
        y=$(( $count * 15 ))
    
        wmctrl -i -r $winID -e"0,${x},${y},-1,-1"

        count=$(( $count + 1 ))
    done

# -i, --inkscape: move only the Inkscape windows
elif [[ "$1" = '-i' ]] || [[ "$1" = '--inkscape' ]]; then
    count=0

    for winID in $(wmctrl -l |cut -f1 -d' ');
    do
        if [[ $(xprop -id $winID | grep -ci "WM_CLASS.*inkscape") = 1 ]]; then
            x=$(( $count * 15 ))
            y=$(( $count * 15 ))

            wmctrl -i -r $winID -e"0,${x},${y},-1,-1"

            count=$(( $count + 1 ))
        fi
    done

# Otherwise try to find windows matching the option string, and move those
else 
    name=$1
    count=0

    for winID in $(wmctrl -l |cut -f1 -d' ');
    do
        if [[ $(xprop -id $winID | grep -ci "WM_CLASS.*${name}") = 1 ]]; then
            x=$(( $count * 15 ))
            y=$(( $count * 15 ))

            wmctrl -i -r $winID -e"0,${x},${y},-1,-1"

            count=$(( $count + 1 ))
        fi
    done
fi
