#!/bin/bash

# launchee

# Slightly moded version of xaos52 script from
# https://forums.bunsenlabs.org/viewtopic.php?pid=11134#p11134
# there has to be at least one parameter, the name of the file to execute
if (( $# == 0 ));then
  echo "Usage: $(basename "$0") executable_name [parameters]"
  exit 1
fi

has_element () {
  local e
  for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  return 1
}

launchee=$(basename "$1")

# test to see if program is already running
declare -a launchee_win_ids
launchee_win_ids=( $(wmctrl -lx | awk -v pattern="$launchee" 'BEGIN {IGNORECASE = 1} $3 ~ pattern {print $1}' ) )
if (( ${#launchee_win_ids[@]} ));
then 
    # means at least one launchee process  must already be running
    active_window_id=$(printf '0x%8x' "$(xdotool getwindowfocus)")
    active_window_id=${active_window_id// /0}

    # is acitve_window_pid one of the already running launchee?
    if has_element "$active_window_id" "${launchee_win_ids[@]}"; then
        # launched app is currently in focus, so do nothing
        xdotool getactivewindow windowminimize
        :
    else
        # launchee instance is not in focus, so raise and bring to focus
        # which one do you bring into focus if there are many?
        # First one is easiest
        wmctrl -i -a "${launchee_win_ids[0]}"
    fi
else
    # start it up
    "$@"&
fi

exit 0