#!/bin/bash
######################################################################
#
# Bashrun2 0.2.2 -- launch applications from interactive bash sessions
# Copyright (C) 2010, 2011 Henning Bekel <h.bekel@googlemail.com>
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
######################################################################

# if no arguments are given, attempt to map an existing run-dialog as
# fast as possible first...
if [[ $# -eq 0 || "$1" == "show" ]]; then
    brwctl bashrun2-run-dialog show
fi

# setup global variables
source __PREFIX__/share/bashrun2/globals

# check external dependencies
source "$bashrun_site/utils"
§check_deps

# bootstrap if cache or data home don't exist
if [[ ! -e "$bashrun_cache_home" || ! -e "$bashrun_data_home" ]]; then
    source "$bashrun_site/bootstrap"
fi

# check if another frontend process is currently running
lock="$bashrun_cache_home/bashrun.lck"
if [[ -f "$lock" ]]; then
    printf '%s\n' "bashrun: locked: $bashrun_cache_home/bashrun.lck exists." >&2
    exit 1
fi

# no other process, so take the lock
touch "$lock"

# remove lock on exit or term
trap '[[ -f "$lock" ]] && /bin/rm "$lock"' EXIT
trap '[[ -f "$lock" ]] && /bin/rm "$lock"' TERM

# set default mode and command
mode="run-dialog"
command="show"

# load frontend functions
source "$bashrun_site/frontend"

# handle options first
until [[ "$1" == "--" || "${1:0:1}" != '-' ]]; do
    case "$1" in
	-v|--version)
 	    version
	    exit 0
 	    ;;
	-h|--help)
 	    usage 
	    exit 0
 	    ;;    
	-m|--mode)
 	    mode="$2"
 	    shift; shift
 	    ;;
	-d|--debug)
	    bashrun_debug=1
	    shift
	    [[ $# -eq 0 ]] && command="debug"
	    ;;
	--remote-control)
	    remote_control_code
	    exit 0
	    ;;	
	*)
	    printf '%s\n' "bashrun2: error: unknown option: $1" >&2
	    usage
	    exit 1
	    ;;
    esac
done

# get info about the selected mode
modeinfo="$bashrun_cache_home/${mode}-info"
if [[ ! -f "$modeinfo" ]]; then
    create_modeinfo
fi
source "$modeinfo"

# get command argument, if any
if [[ $# -gt 0 && "$1" != "--" ]]; then
    command="$1"
    shift
fi

# get arguments and possible terminal options (after "--")
declare -a args
termopts=""

if [[ $# -gt 0 ]]; then
    target="args"    
    for arg; do

	if [[ "$arg" == "--" ]]; then
	    target="term"
	    continue
	fi

	if [[ "$target" == "args" ]]; then
	    args[${#args[@]}]="$arg"
	else
	    termopts+=" $arg"
	fi
    done
    termopts=${termopts/ /}
fi

# launch a new instance if necessary...
launched=0

if ! brwctl bashrun2-$mode &>/dev/null; then # no existing instance
    
    # don't launch a new instance for these commands:
    if [[ "$command" =~ ^(exit|quit)$ ]]; then
	exit 1
    else
	# attempt to launch a new instance...
	launch
	launched=1

	# don't apply these commands on a new instance:
	if [[ "$command" =~ ^(show|toggle|smart|reload|restart|debug)$ ]]; then
	    exit 0
	fi
    fi
fi

# prepare §window class if necessary
[[ launched -eq 0 ]] && source_window

# handle command
case "$command" in
    show)
	§window.map &>/dev/null
	;;
    hide)
	§window.unmap &>/dev/null
	;;	
    toggle)
	§window.toggle &>/dev/null
	;;
    smart)
	§window.toggle_smart &>/dev/null
	;;
    wid)
	printf '%s\n' "$wid"
	;;
    pid)
	pidfile="${XDG_CACHE_HOME:-$HOME/.cache}/bashrun2/$mode-pid"
	if wait_until '[[ -f "$pidfile" ]]'; then
	    printf '%s\n' "$(<$pidfile)"
	else
	    exit 1
	fi
	;;
    su)
	if [[ ${#args[@]} -gt 0 ]]; then
	    remote su-run "${args[@]}"
	else
	    printf '%s\n' \
		"bashrun2: error: command \`su' requires at least one argument: <cmd>" >&2
	    exit 1
	fi
	;;
    do)
	if [[ ${#args[@]} -gt 0 ]]; then
	    remote "${args[@]}"
	else
	    printf '%s\n' \
		"bashrun2: error: command \`do' requires at least one argument: <action> [<cmd>]" >&2
	    exit 1
	fi
	;;
    reload)
	remote reload
	;;
    restart)
	remote quit
	export bashrun_debug
	/bin/rm "$lock" &>/dev/null
	exec bashrun2 -m "$mode" -- $termopts
	;;
    debug)
	remote debug
	§window.map &>/dev/null
	;;
    exit|quit)
	remote quit
	;;    
    *)
	printf '%s\n' "bashrun2: error: unknown command: $command" >&2
	exit 1
esac 
exit 0
