#!/usr/bin/env bash

PACKAGE=piedock-instant-`uname -m`.bin
TEMPLATE=piedock-instant

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

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

mkdir $TEMPLATE "$TEMPLATE/bin" "$TEMPLATE/conf" "$TEMPLATE/icons" || {
	echo "$TEMPLATE cannot be created"
	exit 1
}

# 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
#!/usr/bin/env bash

BIN=piedock

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

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

	local F="\${BIN}rc"
	local RC="\${HOME}/.\$F"

	# check for rc file in home first
	[ -f "\$RC" ] || {
		RC="conf/\$F"

		# realize local configuration template
		[ -f "\$RC" ] &&
			grep "${TEMPLATE}/icons\"" "\$RC" &>/dev/null && {
				local T="conf/.tmp"

				cp \$RC \$T &&
					cat \$T | sed -e "s_\".*${TEMPLATE}/icons\"_\"\`pwd\`/icons\"_g;" > \$RC &&
					rm \$T
			}
	}

	bin/\$BIN -r \$RC &
}

stop()
{
	pkill \$BIN
}

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
#!/usr/bin/env bash

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

echo -n "Configuring ... "
RC=$TEMPLATE/conf/piedockrc APP_ICONS_PATH=$TEMPLATE/applications $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
has grabbed one of the trigger keys or buttons already. In that case
you'll have to modify
$TEMPLATE/conf/piedockrc
to use other keys. Then restart PieDock (see below).

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

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 use one of the following combinations to make the menu
appear:

    Shift + scroll wheel up
    Shift + scroll wheel down

EEOF

exit
EOF

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

chmod a+x $PACKAGE
