#!/bin/bash
# Etersoft, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2015, 2017
# 2010-2015, 2017 (c) Vitaly Lipatov <lav@etersoft.ru>
# 2012 (c) Denis Baranov <baraka@etersoft.ru>
# Без параметров - список полок
# с названием полки - список бутылок
# с полкой/бутылкой - вход, если есть.

# Переводит пользователя под пользователя wine
# Устанавливает авторизацию для доступа к Иксам
# Настраивает wine на соотв. рабочий каталог
# Использует sudo su - wine и xhost
# TODO: добавить поддержку chroot, внутренних скриптов настройки (монтирования), иксов
# TODO: добавить поиск
# TODO: добавить перемещение

PROGRAM_DESCRIPTION="Etersoft's racks and bottles handler. (c) 2006-2015, 2017"

if [ "$UID" = "0" ]; then
	echo "It is forbidden to run swine as root"
	exit 1
fi

if [ "$LANG" = "C" ] ; then
	echo "Don't run me in C locale (check $ locale output)"
	exit 1
fi

### copied from etersoft-build-utils common

# FIXME on Android: FIX ME! implement ttyname_r() bionic/libc/bionic/stubs.c:366
inputisatty()
{
	# check stdin
	tty -s 2>/dev/null
}

isatty()
{
	# check stdout
	test -t 1
}

isatty2()
{
	# check stderr
	test -t 2
}

check_tty()
{
	isatty2 || return

	# Set a sane TERM required for tput
	[ -n "$TERM" ] || TERM=dumb
	export TERM

	# egrep from busybox may not --color
	# egrep from MacOS print help to stderr
	if egrep --help 2>&1 | grep -q -- "--color" ; then
		export EGREPCOLOR="--color"
	fi

	which tput >/dev/null 2>/dev/null || return
	# FreeBSD does not support tput -S
	echo | tput -S >/dev/null 2>/dev/null || return
	[ -z "$USETTY" ] || return
	export USETTY=1
}

: ${BLACK:=0} ${RED:=1} ${GREEN:=2} ${YELLOW:=3} ${BLUE:=4} ${MAGENTA:=5} ${CYAN:=6} ${WHITE:=7}

set_boldcolor()
{
	[ "$USETTY" = "1" ] || return
	{
		echo bold
		echo setaf $1
	} |tput -S
}

restore_color()
{
	[ "$USETTY" = "1" ] || return
	{
		echo op; # set Original color Pair.
		echo sgr0; # turn off all special graphics mode (bold in our case).
	} |tput -S
}

echover()
{
    [ -z "$verbose" ] && return
    echo "$*" >&2
}

# echo string without EOL
echon()
{
	# default /bin/sh on MacOS does not recognize -n
	/bin/echo -n "$@"
}

# Print command line and run command line
showcmd()
{
	if [ -z "$quiet" ] ; then
		set_boldcolor $GREEN
		local PROMTSIG="\$"
		[ "$EFFUID" = 0 ] && PROMTSIG="#"
		echo " $PROMTSIG $@"
		restore_color
	fi >&2
}

# Print command line and run command line
docmd()
{
	showcmd "$@$EXTRA_SHOWDOCMD"
#CHECKME
	"$@"
}


print_message()
{
	local DESC="$1"
	shift
	echo "$DESC in $(basename $0): $@"
}

# Print error message and stop the program
fatal()
{
	print_message Error "$@" >&2
	exit 1
}

check_ssh_key()
{
	echo "Check access to SSH private key..."
	ssh-add -l && return
	ssh-add $SSH_KEYFILE && return
	fatal "Please, check your ssh-agent settings."
}

##### end of the copy

check_swine_alias()
{
    local SWINEALIAS=/etc/etersoft/swine.alias
    [ -r "$SWINEALIAS" ] || fatal "No $SWINEALIAS file"
    local RES=$(grep "^$1 " $SWINEALIAS)
    [ -n "$RES" ] || return
    echo "$RES" | sed -e "s|.* ||g"
}

try_hostalias()
{
	# allow only one entry
	[ -n "$REALCELLARNAME" ] && return 1

	# redefine default bottle from the first script arg
	REALCELLARNAME=$(check_swine_alias "$1")
	if [ -n "$REALCELLARNAME" ] ; then
		CELLARNAME=$REALCELLARNAME
		return 0
	fi
	return 1
}

# you can override it in /etc/etersoft/swine.conf
# default bottle
CELLARNAME=eterhack
# local company domain
DOMAINNAME=office.etersoft.ru
# remote ssh alias
SERVERNAME=office
# opt args for ssh (see eterbug #10725)
SSH_OPTS="-c arcfour,blowfish-cbc,aes256-ctr,aes192-ctr,aes128-ctr -o Compression=no -o ControlMaster=auto -o ControlPath=~/tmp/ssh_mux_%h_%p_%r -o ControlPersist=4h "
# default shell to run
COMMANDTORUN=bash
# server side temp dir for tarballs for download
ARDIR=/var/ftp/tmp/wine
# root bottle dir
BOTDIR=/net/wine
# wine user
WINEUSER=wine

[ -r /etc/etersoft/swine.conf ] && . /etc/etersoft/swine.conf

# hack to do options unpositional
case "$1" in
	-*)
	;;
	*)
		try_hostalias "$1" && shift
	;;
esac

if [ "$1" = "--internal" ] ; then
	shift
	INTERNAL=1
fi

if [ "$1" = "-l" ] || [ "$1" = "--local" ] ; then
	shift
	LOCALRUN=1
fi

if [ "$1" = "-t" ] || [ "$1" = "--nx" ] ; then
	shift
	NXMODE=1
fi

if [ "$1" = "-s" ] || [ "$1" = "--ssh" ] ; then
	shift
	SSHTUNNEL=1
fi

if [ "$1" = "-d" ] || [ "$1" = "--download" ] ; then
	shift
	DOWNLOAD=1
fi

if [ "$1" = "-u" ] ; then
	UNPACK_TARBALL=1
	shift
fi

#if [ "$1" = "-h" ] || [ "$1" = "--host" ] ; then
#	shift
#	if [ -z "$1" ] ; then
#		echo "Missing host name (Use --help for help)"
#		exit 1
#	fi
#	CELLARNAME=$1
#	shift
#fi

if [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then
		echo "$PROGRAM_DESCRIPTION"
		echo "Check http://winehq.org.ru/swine for description in Russian"
		echo "Usage:"
		echo "swine [host alias name] [options] [rackname][/][bottle name] [command]"
		echo "      --remove          remove the bottle"
		#echo "      --search [-s] name     search for bottle"
		echo "      --clone [-o] rackname [privatebottle]       clone the bottle to private bottle"
		echo "      --download [-d] [rackname][/][bottle name]  download tarball with bottle"
		echo "      -u                                          unpack tarball after download"
		#echo "      --move  rack/bottle rack/bottle   move  the bottle to other rack"
		echo "      --private [-p] privatebottle       use private bottle"
		echo "      --local [-l]             use local host instead remote host"
		#echo "      --host [-h]             use another host for bottle"
		echo "      --recursive [-r]         recursive bottle list"
		echo "      --force                  force login to used bottle"
		echo "      --ssh [-s]               use ssh tunnel instead direct DISPLAY (default for remote connections)"
		echo "      --nx [-t]               use NX protocol for bottle (only for local connections)"
		echo "      --create [-c]            create the bottle"
		echo "      --quiet [-q]             make silent output"
		echo
		echo "Examples:"
		echo " $ swine [rackname] -- lists available racks & bottles"
		echo " $ swine vanilla -d bugs/1234 -- download tarball for bugs/1234 wine prefix from vanilla container"
		exit 0
fi

case "$1" in
	-p|--private|--remove|-o|--clone|-r|--recursive|--force|-c|--create|-q|-quiet)
	# pass to internal
	;;
	-*|--*)
		# do not handle any other params here
		echo "Unknown parameter '$1'. Use -h or --help for get help." >&2
		exit 1
	;;
	*)
		try_hostalias "$1" && shift
	;;
esac


REMOTECMD=
# out of the office
if [ -z "$LOCALRUN" ] && [ `hostname -d` != $DOMAINNAME ] ; then
	echo "Running out of the Etersoft office (your domain is $(hostname -d)"
	REMOTECMD="ssh -t -Y -C -A $SSH_OPTS $SERVERNAME"
	if [ -z "$NXMODE$SSHTUNNEL" ] ; then
		echo "Use ssh tunnel"
		SSHTUNNEL=1
	fi
fi

if [ -z "$INTERNAL" ] ; then
	# Check for repeatable entry
	if [ -n "$ORIG_USER" ] && [ "$USER" = "$WINEUSER" ] && [ `hostname -s` = "$CELLARNAME" ] ; then
		echo "You are already in wine '$CELLARNAME' :)" >&2
		exit 1
	fi

	# Заходим локально
	# TODO: obsoleted
	if false && [ -n "$LOCALRUN" ] ; then
		export CELLARNAME=`hostname -s`
		# TODO: replace with xauth
		# read man xhost
		IP=+$HOSTNAME
		test -z "$IP" && IP=+localhost
		# if DISPLAY is local, allow for local
		echo $DISPLAY | grep -q "^:" && IP=local:
		xhost $IP

		echo "Local bottling to $CELLARNAME (allow X access for $IP)"
		# Put some env vars through userchange, f.i. NXSESSIONID
		sudo /bin/su - $WINEUSER -c "CELLARNAME=$CELLARNAME NXSESSIONID=$NXSESSIONID swine --internal $USER --display $DISPLAY $*"
		exit

	elif [ -n "$DOWNLOAD" ] ; then

		[ -z "$1" ] && fatal "Missing bottle name for download"
		DOWNLOAD_BOTTLE=$1
		shift

		check_ssh_key || exit

		#[ -d "$TMPDIR" ] || TMPDIR=/tmp
		DOWNLOADDIR=$(pwd)

		DIR_BOTTLE=`dirname $DOWNLOAD_BOTTLE`
		[ "$DIR_BOTTLE" = "." ] && fatal "Incorrect bottle name $DOWNLOAD_BOTTLE"

		TARNAME=wine-`basename $DOWNLOAD_BOTTLE`
		TARFORMAT=tar.7z
		PATHCELLARTMP=$ARDIR/$TARNAME.$TARFORMAT
		PATH_BOTTLE="$BOTDIR/bottles/$DIR_BOTTLE"

		# TODO: use pipe and <<< like in gluster script
		remote_run()
		{
			$REMOTECMD ssh $SSH_OPTS $WINEUSER@$CELLARNAME "$@"
		}

		if remote_run test -s $PATHCELLARTMP ; then
			echo "Tarball $SERVERNAME:$CELLARNAME:$PATHCELLARTMP already exists, do not recreate. Skipping."
		else
			echo "Remote archiving bottle $PATH_BOTTLE/.$TARNAME to $CELLARNAME:$PATHCELLARTMP tarball"
			# remove if failed
			if ! remote_run "erc --quiet create $PATHCELLARTMP $PATH_BOTTLE/.$TARNAME" ; then
				remote_run rm -v $PATHCELLARTMP
				exit 1
			fi
		fi
		echo "Downloading tarball to local place $DOWNLOADDIR/$TARNAME.$TARFORMAT"
		docmd rsync -avc --partial --progress -e "$REMOTECMD ssh $SSH_OPTS" $WINEUSER@$CELLARNAME:$PATHCELLARTMP $DOWNLOADDIR/$TARNAME.$TARFORMAT || exit

		epm assure erc || exit
		if ! docmd erc test $DOWNLOADDIR/$TARNAME.$TARFORMAT ; then
			echo "Tarball is broken, remove it from all!"
			echo "Removing local tarball..."
			rm -v $DOWNLOADDIR/$TARNAME.$TARFORMAT
			echo "Removing remote tarball $SERVERNAME:$CELLARNAME:$PATHCELLARTMP ..."
			remote_run rm -v $PATHCELLARTMP
			exit 1
		fi

		echo "Removing remote tarball $SERVERNAME:$CELLARNAME:$PATHCELLARTMP ..."
		remote_run rm -v $PATHCELLARTMP

		if [ -n "$UNPACK_TARBALL" ] ; then
			echo "Unpacking bottle .$TARNAME to the current dir $(pwd)"
			erc --quiet extract $DOWNLOADDIR/$TARNAME.$TARFORMAT || exit

			echo "Removing local tarball..."
			rm -v $DOWNLOADDIR/$TARNAME.$TARFORMAT
		else
			echo "Completed. You can unpack the tarball with command 'erc $DOWNLOADDIR/$TARNAME.$TARFORMAT'"
		fi
		exit 0

	elif [ "$USER" != "$WINEUSER" ] || [ `hostname -s` != "$CELLARNAME" ] ; then

		# Конектимся через nx
		if [ -n "$NXMODE" ] ; then
		    echo "Run in NX mode"
		    [ -n "$NXCLIENT" ] || NXCLIENT="opennx"
		    [ -n "$NXCLIENT_CONFIG" ] || NXCLIENT_CONFIG="$HOME/.nx/config/swine.nxs"
		    if [ ! -e "$NXCLIENT_CONFIG" ]; then
			echo "Copying default nxclient configuration..."
			mkdir -p `dirname "$NXCLIENT_CONFIG"`
			cp /etc/etersoft/swine.nxs $NXCLIENT_CONFIG
		    fi
		    [ -n "$NXCOMMAND" ] || NXCOMMAND="xterm -e swine -l $@"
		    sed -i -e "s|<option key=\"Server host\" value=\".*\"|<option key=\"Server host\" value=\"$CELLARNAME\"|g" $NXCLIENT_CONFIG
		    sed -i -e "s|<option key=\"Command line\" value=\".*\"|<option key=\"Command line\" value=\"$NXCOMMAND\"|g" $NXCLIENT_CONFIG
		    $NXCLIENT --session "$NXCLIENT_CONFIG"
		    exit 0
		fi

		check_ssh_key || exit

		# FIXME: xhost contains some security issues
		#export ORIG_USER=$USER
		if [ -n "$SSHTUNNEL" ] ; then
			OURDISPLAY=NONE
			SSHOPTIONS="-Y"
		else
			xhost +$CELLARNAME
			OURDISPLAY=$DISPLAY
			HOSTFROM=${OURDISPLAY/:*/}
			# FIXME: in hope we will can ping from cellar back to our host
			CURRENTHOST=$(hostname)
			[ -z "$HOSTFROM" ] && OURDISPLAY=$CURRENTHOST$OURDISPLAY
			SSHOPTIONS=""
		fi

		[ -n "$QUIET" ] || echo "\$> $REMOTECMD ssh -t $SSHOPTIONS $SSH_OPTS $WINEUSER@$CELLARNAME swine --internal $USER --display $OURDISPLAY $@"
		$REMOTECMD ssh -t $SSHOPTIONS $SSH_OPTS $WINEUSER@$CELLARNAME swine --internal $USER --display $OURDISPLAY "$@"
		exit
	fi

	fatal "Logical error. Direct run in cellar is unsupported."
fi

##########################################################################################
# Internal entry on cellar host
##########################################################################################

export CELLARNAME=`hostname -s`

# like BOTDIR, but locally
BOTPATH=~/bottles

export ORIG_USER=$1
shift

if [ "$1" = "--display" ] ; then
	shift
	if [ ! "$1" = "NONE" ] ; then
		export DISPLAY=$1
	fi
	shift
fi

get_runfile()
{
	echo $HOME/tmp/run-${RACK//\//_}-$BOTTLE
}

get_holder()
{
	#local BOTTLE=$1
	head -n 1 $TPBOTTLE | cut -d " " -f 2
	# TODO: print out name of the person
}

print_comment()
{
	local COMFILE="$1/comment"
	if [ -r "$COMFILE" ] ; then
		head -n1 < "$COMFILE" | cat
	fi
}

# Save comment to
set_comment()
{
	local COMFILE="$1/comment"
	shift
	local COMMENT="$@"
	if [ -n "$COMMENT" ] ; then
		touch "$COMFILE"
		if [ -w "$COMFILE" ] ; then
			echo "Just update comment: '$COMMENT'"
		else
			echo "Error: can't write comment"
			return 1
		fi
		echo "$COMMENT" | cat > "$COMFILE" || return 1
	else
		return 1
	fi
	return 0
}

print_creator()
{
	local COMFILE="$1/creator"
	if [ -r "$COMFILE" ] ; then
		echo -n ", created by "
		head -n1 < "$COMFILE" | cat
	fi
}

set_creator()
{
	local COMFILE="$1/creator"
	shift
	echo "$ORIG_USER" > "$COMFILE" || return 1
	return 0
}

# Print list racks and bottles, call print_list RACK [step N]
print_list()
{
	local LB RACK=$1 RACKCOM BOTCOM STEP=0
	shift
	if [ "$1" = "step" ] ; then
		shift
		STEP=$1
		shift
	else
		if [ -z "$QUIET" ] ; then
			if [ -z "$RACK" ] ; then
				echo "List of available racks on $CELLARNAME:"
			else
				RACKCOM=$(print_comment "$BOTPATH/$RACK")
				[ -n "$RACKCOM" ] && RACKCOM=" ($RACKCOM)"
				echo "List of available bottles in the '$RACK'$RACKCOM rack:"
			fi
		fi
	fi

	# List available racks
	LD=`(cd $BOTPATH ; find $RACK -maxdepth 1 -type d 2>/dev/null | grep -v "^$RACK\$" | grep -v "^\.\$" | grep -v "\.wine" | sort | sed -e "s|^\./||g")`
	for INRA in $LD ; do
		if [ -n "$QUIET" ] ; then
			echo "$INRA"
		else
			RACKCOM=$(print_comment "$BOTPATH/$INRA")
			printf "%-${STEP}s" ""
			printf "  %-30s %s\n" "[R] $(basename $INRA)" "$RACKCOM"
		fi
		if [ -n "$RECURSIVE" ]  ; then
			print_list "$INRA" step $(($STEP + 4))
			[ "$STEP" = "0" ] && [ -z "$QUIET" ] && echo
		fi
	done

	# List available bottles
	LB=`(cd $BOTPATH ; find $RACK -maxdepth 1 -type d -name ".wine-*" 2>/dev/null | grep -v "^$RACK\$" | sort)`
	for FD in $LB ; do
		BOTTLE=$(echo $FD | sed 's|.*\.wine-||g')

		if [ -n "$QUIET" ] ; then
			echo "$RACK/$BOTTLE"
		else
			TPBOTTLE=$(get_runfile)
			PROGNAME="$BOTTLE"
			[ -e "$TPBOTTLE" ] && PROGNAME+="  (USED by $(get_holder))"
			BOTCOM=$(print_comment "$BOTPATH/$RACK/.wine-$BOTTLE")
			BOTCRE=$(print_creator "$BOTPATH/$RACK/.wine-$BOTTLE")
			printf "%-${STEP}s" ""
			printf "  %-$((30 - $STEP))s %s\n" "$PROGNAME" "$BOTCOM$BOTCRE"
		fi
	done

	# Print if the rack is empty
	if [ -z "$LB$LD" ] && [ -n "$RACK" ] && [ -z "$QUIET" ] ; then
		printf "%-${STEP}s" ""
		echo "  empty"
		return
	fi

}

# Check for rack part (check real dir exists too)
get_rack()
{
	local DN=$(dirname "$1")
	if [ -d "$BOTPATH/$1" ] || echo "$1" | grep '.*/$' >/dev/null; then
		echo "$1" | sed 's|/$||g'
		return
	fi
	if [ "$DN" = "." ] ; then
		echo "$1" | sed 's|/.*||g'
	else
		echo "$DN"
	fi
}

# Check for bottle part (check real dir exists too)
get_bottle()
{
	local BN=$(basename "$1")
	if [ -d "$BOTPATH/$1" ] || echo "$1" | grep '.*/$' >/dev/null; then
		echo ""
		return
	fi
	if [ "$BN" = "$1" ] || [ "$BN/" = "$1" ] ; then
		echo ""
	else
		echo "$BN"
	fi
}

# FIXME: do it more correctly
FORCE=
REMOVE=
CREATE=
PRIVATE=
RECURSIVE=
QUIET=

if [ "$1" = "--force" ] ; then
	shift
	FORCE=yes
fi

if [ "$1" = "-c" ] ; then
	shift
	CREATE=yes
fi

if [ "$1" = "-p" ] || [ "$1" = "-private" ] ; then
	shift
	PRIVATE=yes
fi

if [ "$1" = "-q" ] || [ "$1" = "--quiet" ] ; then
	shift
	QUIET=yes
fi

if [ "$1" = "-r" ] || [ "$1" = "--recursive" ] ; then
	shift
	RECURSIVE=yes
fi

# need twice for hack -q -r and -r -q order
if [ "$1" = "-q" ] || [ "$1" = "--quiet" ] ; then
	shift
	QUIET=yes
fi

if [ "$1" = "-o" ] || [ "$1" = "--clone" ] ; then
	shift
	CLONE=yes
fi

if [ "$1" = "--remove" ] ; then
	shift
	REMOVE=yes
fi

COMNAME=$1
shift

if [ "$1" = "-c" ] ; then
	CREATE=yes
	shift
fi

if [ "$1" = "--force" ] ; then
	FORCE=yes
	shift
fi

if [ "$1" = "-p" ] || [ "$1" = "-private" ] ; then
	shift
	PRIVATE=yes
fi

if [ "$1" = "-r" ] || [ "$1" = "--recursive" ] ; then
	shift
	RECURSIVE=yes
fi

if [ "$1" = "-q" ] || [ "$1" = "--quiet" ] ; then
	shift
	QUIET=yes
fi

if [ "$1" = "-o" ] || [ "$1" = "--clone" ] ; then
	shift
	CLONE=yes
fi

if [ "$1" = "--remove" ] ; then
	shift
	REMOVE=yes
fi

# run without args: lists available racks
if [ -z "$COMNAME" ] ; then
	if [ -n "$PRIVATE" ] ; then
		RACK="peoples/$ORIG_USER"
	else
		RACK=""
	fi
	print_list "$RACK"
	exit 0
fi

[ -z "$QUIET" ] || echo "$PROGRAM_DESCRIPTION"

RACK=$(get_rack "$COMNAME")
BOTTLE=$(get_bottle "$COMNAME")

if [ -n "$PRIVATE" ] ; then
	RACK="peoples/$ORIG_USER"
	BOTTLE="$COMNAME"
fi

##################################################################3
# Run with rack name only
if [ -z "$BOTTLE" ] ; then

	# Create rack if needed
	if [ -n "$CREATE" ] ; then
		if [ -e "$BOTPATH/$RACK" ] ; then
			echo "$BOTPATH/$RACK already exists."
			set_comment "$BOTPATH/$RACK" "$@"
			exit $?
		fi
		echo Create "$BOTPATH/$RACK"
		mkdir -p "$BOTPATH/$RACK" || exit 1
		set_comment "$BOTPATH/$RACK" "$@"
		exit 0
	fi

	# List bottles
	if [ -d "$BOTPATH/$RACK" ] ; then
		print_list "$RACK"
	else
		echo "'$RACK' rack is not exists. You can create it with command 'swine $RACK -c [Rack description]'"
	fi
	exit 0
fi

# If DISPLAY is broken
if ! xset -b ; then
	echo "Warning: you have no access to your X server from $CELLARNAME. Check with ps -ax | grep X for nolisten tcp. Check local DISPLAY variable."
	echo "Also you can use swine without direct DISPLAY with --ssh option (for local connections)."
fi


################################################################
# Run with full path to bottle
export WINEPREFIX="$BOTPATH/$RACK/.wine-$BOTTLE"

TPBOTTLE=$(get_runfile)
COMNAME="$RACK/$BOTTLE"

if [ -n "$CLONE" ] ; then
	if [ -d "$WINEPREFIX" ] ; then
		LOCALBOTTLE="$BOTPATH/peoples/$ORIG_USER"
		echo "Copying `basename $WINEPREFIX` to peoples/$ORIG_USER"
		mkdir -p "$LOCALBOTTLE"
		# -v
		cp -a "$WINEPREFIX" "$LOCALBOTTLE"
	else
		echo "Bottle $BOTTLE is missed"
	fi
	exit 0
fi

if [ -n "$FORCE" ] ; then
	rm -f "$TPBOTTLE"
fi

if [ -f "$TPBOTTLE" ] ; then
	BOTTLEUSER=$(cat "$TPBOTTLE")
	if [ "$BOTTLEUSER" = "$ORIG_USER" ] ; then
		echo "Note: you already entered anywhere"
	else
		echo "Error: $COMNAME bottle is already used by $(get_holder). You can override it with --force key"
		exit 1
	fi
fi

if [ -n "$REMOVE" ] ; then
	chmod u+rwX "$WINEPREFIX" -R
	rm -rf "$WINEPREFIX" || exit 1
	echo "Bottle $RACK/$BOTTLE succesfully removed"
	exit 0
fi

# Set we use this bottle
echo "$ORIG_USER" > "$TPBOTTLE" || exit 1

if [ -d "$WINEPREFIX" ] ; then
	if [ -n "$CREATE" ] ; then
		set_comment "$WINEPREFIX" "$@"
		rm -f "$TPBOTTLE"
		exit 0
	fi
else
	if [ -n "$CREATE" ] ; then
		# initial wine creating
		mkdir -p "$WINEPREFIX"
		# wine vanilla needs precreated prefix and some command to run
		wine cmd.exe /C ver
		# disable autoupdate prefix
		echo "disable" > "$WINEPREFIX/.update-timestamp"
		set_comment "$WINEPREFIX" "$@"
		set_creator "$WINEPREFIX" "$@"
		exit 0
	else
		echo "Error: '$COMNAME' bottle does NOT exist, run with -c key for create"
		rm -f "$TPBOTTLE"
		exit 1
	fi
fi

echo "Your are on `hostname` host in '$COMNAME' Wine bottle$(print_creator $WINEPREFIX)..."
cd "$WINEPREFIX" || exit
export PS1="<wine@$CELLARNAME bottle $COMNAME>\$ "
[ -n "$1" ] && COMMANDTORUN="$*"
$COMMANDTORUN
rm -f "$TPBOTTLE"
