#!/bin/bash

PACKAGE=PieDockInstant-`uname -m`.bin
TEMPLATE=PieDockInstant

[ -d $TEMPLATE ] && {
	echo "$TEMPLATE already exists"
	exit -1
}

touch $PACKAGE || {
	echo "$PACKAGE cannot be created"
	exit -1
}

if ! mkdir $TEMPLATE ||
	! mkdir "$TEMPLATE/bin" ||
	! mkdir "$TEMPLATE/conf" ||
	! mkdir "$TEMPLATE/icons"; then
	echo "$TEMPLATE cannot be created"
	exit -1
fi

# copy setup script
{
	SETUP=sh/setup

	[ -x "$SETUP" ] || {
		echo "$SETUP script not found"
		exit -1
	}

	cp $SETUP $TEMPLATE/setup || {
		echo "cannot move $SETUP in place"
		exit -1
	}
}

for B in src/PieDock utils/PieDockUtils
do
	[ -r $B ] || {
		echo "$B not found, use ./configure && make to build it"
		exit -1
	}

	strip $B
	cp $B "$TEMPLATE/bin/"
done

# write start/stop script
cat <<EOF > $TEMPLATE/pd
#!/bin/bash

BIN=PieDock

[ -z "\$1" ] && {
	echo "usage: \`basename \$0\` (start|stop|status|restart)..."
	exit -1
}

function start()
{
	cd \`dirname \$0\`

	# update configuration file
	[ -f conf/PieDockrc ] &&
		grep "${TEMPLATE}/icons\"" conf/PieDockrc &>/dev/null && {
		C=conf/PieDockrc
		T=conf/.PieDockrc-temporary
		cp \$C \$T &&
			cat \$T | sed -e "s_\".*${TEMPLATE}/icons\"_\"\`pwd\`/icons\"_g;" > \$C &&
			rm \$T
	}

	bin/\$BIN -r conf/\${BIN}rc &
}

function stop()
{
	pkill \$BIN
}

function status()
{
	pgrep \$BIN
}

for ARG in \$@
do
	case \$ARG in
		star*)
			start
			;;
		sto*)
			stop
			;;
		stat*)
			status
			;;
		res*)
			stop
			start
			;;
		*)
			echo "unknown parameter \"\$ARG\""
			;;
	esac
done

EOF

chmod a+x $TEMPLATE/pd

# write install script
cat <<EOF > $PACKAGE
#!/bin/bash

cat <<EEOF
PieDock Instant
http://markusfisch.de/PieDock

EEOF

echo -n "Extracting archive ... "
sed -e '1,/^exit\$/d' "\$0" | tar xzf -
echo "ok"

echo -n "Configuring ... "
RC=$TEMPLATE/conf/PieDockrc ICON_PATH=$TEMPLATE/icons $TEMPLATE/setup
rm -f $TEMPLATE/setup
echo "ok"

echo -n "Starting PieDock ... "
$TEMPLATE/pd start &
echo "ok"

cat <<EEOF

If you got "X Error of failed request:  BadAccess", some other program
have grabbed one of those keys or buttons already. In that case you'll
have to modify
$TEMPLATE/conf/PieDockrc
to use other keys. Restart after doing so.

If the menu isn't transparent (you have a black box behind the menu),
you have to remove the line "compositing 1" from
$TEMPLATE/conf/PieDockrc
and start again.

Start PieDock if it is not running:

    \$ $TEMPLATE/pd start

Restart PieDock after a configuration change:

    \$ $TEMPLATE/pd restart

Stop PieDock:

    \$ $TEMPLATE/pd stop

You may press one of the following combinations to make the menu
appear:

    Windows-key + left mouse button
    Windows-key + scroll wheel up
    Windows-key + scroll wheel down

EEOF

exit
EOF

tar czf - $TEMPLATE >> $PACKAGE
rm -rf $TEMPLATE

chmod a+x $PACKAGE
