#!/bin/bash
#    half-maximize
#    Copyright © 2012 Jeff Epler
#
#    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
usage () {
    echo "$(basename $0): Half-maximize a window"
    echo
    echo "Usage: $(basename $0) [-h] [-w win] [0l|0r|1l|1r|q|w|e|r]"
    echo ""
    echo " -w: specify window (default, :ACTIVE:, means focused window)"
    echo " -h: view this help"
    echo ""
    echo " 0l, q: maximize window to left  half of monitor 0"
    echo " 0r, w: maximize window to right half of monitor 0"
    echo " 1l, e: maximize window to left  half of monitor 1"
    echo " 1r, r: maximize window to right half of monitor 1"
    echo ""
    echo "Configure your monitor(s) in the file ~/.halfmaxrc:"
    echo ""
    echo "    S0W=nnn # width of primary monitor (in pixels)"
    echo "    S1W=nnn # width of secondary monitor (in pixels)"
    echo ""
    echo "(the primary monitor is hardcoded to start at pixel 0"
    echo "and the secondary monitor is on its right)"
}

WIN=:ACTIVE:
while getopts "w:h" opt; do
    case "$opt" in
    w) WIN=$OPTARG ;;
    h) usage; exit 0 ;;
    ?) usage; exit 1 ;;
    esac
done
shift $(($OPTIND-1))

S0W=1600
S1W=1920

if [ -f $HOME/.halfmaxrc ]; then . $HOME/.halfmaxrc; fi

wmctrl -r $WIN -b remove,maximized_horz
wmctrl -r $WIN -b add,maximized_vert
case "${1-0l}" in
    q|0l) wmctrl -r $WIN -e 1,0,-1,$((S0W/2)),-1      ;;
    w|0r) wmctrl -r $WIN -e 1,$((S0W/2)),-1,$((S0W/2)),-1     ;;
    e|1l) wmctrl -r $WIN -e 1,$S0W,-1,$((S1W/2)),-1    ;;
    r|1r) wmctrl -r $WIN -e 1,$((S0W+S1W/2)),-1,$((S1W/2)),-1    ;;
esac
