#!/bin/bash

hold=false
watch=false
watchtime=2
if [[ $1 = -h* ]]; then
    hold=true
    shift
elif [[ $1 = -w* || $1 = -n ]]; then
    watch=true
    watchtime=$2
    shift 2
fi

if [[ $# -lt 1 ]]; then
    xmessage 'need command'
    exit 2
fi

LIGHT=false
[[ -r ~/.light ]] && . ~/.light

progname=$(basename "$0")

case $progname in
    mrun)       terminal=mate-terminal ;;
    grun)       terminal=gnome-terminal ;;
    *)
        terminal=xterm
        if $LIGHT; then
            resname=LightXTerm
        else
            resname=XTerm
        fi ;;
esac

if [[ $SHELL = *csh ]]; then
    shellcmd="$SHELL -c"
elif [[ $SHELL = *fish ]]; then
    if command -v zsh &>/dev/null; then
        shellcmd="zsh -i -c"
    else
        shellcmd="bash -i -c"
    fi
else
    shellcmd="$SHELL -i -c"
fi

if $watch; then
    title="Xwatch $*"
else
    title="$*"
fi

args=()
if [[ $terminal == xterm ]]; then
    args+=(-name "$resname" -T "$title" -n "$title")
    hold_args=(-hold -sl 1000000)
    watch_args=(-sl 0 +sb)
    trailing=(-e)
    hold_code='echo \(close window\)'
else
    args+=(--title "$title")
    hold_args=()
    watch_args=()
    trailing=(--)
    hold_code='echo \(hit enter\); read'
fi

COMMAND=$(printf " %q" "$@")

if $hold; then
    $terminal "${args[@]}" "${hold_args[@]}" "${trailing[@]}" \
        $shellcmd "$COMMAND; echo \[exit \$?\]; $hold_code" >&/dev/null &
elif $watch; then
    $terminal "${args[@]}" "${watch_args[@]}" "${trailing[@]}" \
        $shellcmd "watch -n $watchtime $COMMAND" >&/dev/null &
else
    if [[ $SHELL = *csh ]]; then
        $terminal "${args[@]}" "${trailing[@]}" \
            $shellcmd "$COMMAND; ret=\$?; if ( \$ret != 0 ) then; echo \[exit \$ret\] \(hit enter\); read; endif" >&/dev/null &
    else
        $terminal "${args[@]}" "${trailing[@]}" \
            $shellcmd "$COMMAND; ret=\$?; if [[ \$ret -ne 0 ]]; then echo \[exit \$ret\] \(hit enter\); read; fi" >&/dev/null &
    fi
fi

