#!/bin/bash
. bean_func.fnc

# 引数が無ければ終了
if [ $# -lt 1 ] ; then
	exit 1
fi

#================================================================================


if [ ! "$1" == "--batch-file" ] ; then
	if [ $(Bean_Ext "${1}") == "bat" ] || [ $(Bean_Ext "${1}") == "cmd" ] ; then
		x-terminal-emulator -e "$0" --batch-file "$@"
		exit 0
	else
		_BAT=0
	fi
else
	shift
	_BAT=1
fi

_WDIR=$(Bean_FullDir "${1}")
_APP=$(basename "${1}")
_ARGS="${_APP}"

shift

if [ $# -gt 0 ] ; then
	for i in "$@" ; do
		if [ "${i:0:1}" == "-" ] ; then
			if [ -e "${i}" ] ; then
				j=$(winepath -w "${i}")
				_ARGS="${_ARGS} \"${j}\""
			else
				_ARGS="${_ARGS} ${i}"
			fi
			
		elif [ "${i:0:1}" == "/" ] ; then
			j=/$(echo "${i}" | awk -F"/" '{print $2}')
			if [ -e "${j}" ] ; then
				k=$(winepath -w "${i}")
				_ARGS="${_ARGS} \"${k}\""
			else
				_ARGS="${_ARGS} ${i}"
			fi
			
		elif [ "${i:0:2}" == "./" ] || [ "${i:0:3}" == "../" ] ; then
			j=$(winepath -w "${i}")
			_ARGS="${_ARGS} \"${j}\""
		
		else
			j=$(Bean_PathConv "${i}")
			_ARGS="${_ARGS} \"${j}\""
		fi
	done
fi

cd "${_WDIR}"
if [ ${_BAT} -gt 0 ] ; then
	if [ $(cat "${_APP}" | grep --ignore-case ^pause | wc -l) -gt 0 ] ; then
		echo "${_ARGS}" | wine cmd 2>/dev/null && \
		echo
		echo
		echo Wineのバグにより、pauseコマンドは正しく動作しません。
		echo Enterを押すと、入力待ちを終えてバッチファイルを閉じます。
		read ans
	else
		echo "${_ARGS}" | wine cmd 2>/dev/null && exit 0
	fi
	exit 1
else
	#wine start "${_ARGS}" & exit 0
	echo "${_ARGS}" | nkf -s | wine cmd 2>/dev/null && exit 0
fi
