#! /bin/sh
# Close named Window of named Application, via AppleScript
#
# Usage: closewindow APPLICATION WINDOW_TITLE [ATTEMPTS]
#
# Where "APPLICATION" is the application name in AppleScript (often the
# program menu name); "WINDOW_TITLE" is the title of the window that you
# want to close, and "ATTEMPTS" is how many times to try, waiting 1 second
# in between for the window to appear (default only try once).
#
# Based on:
#
# http://superuser.com/questions/526624/how-do-i-close-a-window-from-an-application-passing-the-file-name
#
# Written by Ewen McNeill <ewen@naos.co.nz>, 2015-08-27
#
#---------------------------------------------------------------------------
# Copyright (c) 2015, Ewen McNeill.  All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#---------------------------------------------------------------------------

PATH="/usr/bin:/bin"
export PATH

if [ -n "$1" -a -n "$2" ]; then
    ATTEMPTS="${3:-1}"     # Default to just trying once
    for ATTEMPT in $(seq 1 "${ATTEMPTS}"); do
        osascript <<EOF
tell application "$1"
  close (every window whose name is "$2")
end tell
EOF
        if [ "${ATTEMPT}" = "${ATTEMPTS}" ]; then
            :
        else
            sleep 1
        fi
    done
else
    echo "Usage: $0 APPLICATION WINDOW_TITLE [ATTEMPTS]" >&2
    exit 1
fi
