#!/bin/bash

cat <<EOF

This will build, install and run PieDock. If there are libraries or tools
missing, this script will try to install them through your local package
management system. In order to do that, you will be required to give your
root password or to run this as root.

Do you want to build, install and run PieDock now (y/n)?
EOF

read A && [[ $A != y ]] && exit 1

# check we're in the right place
[ -x configure ] || {
	cd ..
	[ -x configure ] || {
		echo "error: missing configure script"
		exit 1
	}
}

# and have a setup script
[ -x sh/setup ] || {
	echo "error: missing setup script"
	exit 1
}

# check for sudo if not run as root
SUDO=
[[ $EUID -ne 0 ]] && {
	SUDO=sudo
	which $SUDO &>/dev/null || {
		echo "error: "
		exit 1
	}
}

for (( RUNS=2; RUNS--; ))
do
	# try to configure build for this system
	./configure && {
		make || {
			echo "error: build failed, check the top most error"
			exit 1
		}

		$SUDO make install || {
			echo "error: installation failed, check the top most error"
			exit 1
		}

		sh/setup || {
			echo "error: setup failed"
			exit 1
		}

		PieDock || {
			echo "error: PieDock failed to start $HOME/.PieDockrc"
			exit 1
		}

		cat <<EOF

Congratulations! PieDock was successfully installed and run!

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

To fine-tune the experience, check out the configuration file at

$HOME/.PieDockrc

You may now erase this directory.

EOF

		break
	}

	ERROR_STRING="error: libraries cannot be installed"

	# try to get libraries on Ubuntu or Debian
	which apt-get &>/dev/null && {
		$SUDO apt-get -y --no-upgrade install g++ \
			libx11-dev \
			libxmu-dev \
			libxrender-dev \
			libxft2-dev \
			libfreetype6-dev \
			libpng-dev || {
			echo $ERROR_STRING
			exit 1
		}

		continue
	}

	# try to get libraries on openSUSE
	which zypper &>/dev/null && {
		# where's Xft on SUSE?
		$SUDO zypper --non-interactive install gcc-c++ \
			make \
			xorg-x11-libX11-devel \
			xorg-x11-libXmu-devel \
			xorg-x11-libXrender-devel \
			freetype2-devel \
			libpng14-devel || {
			echo $ERROR_STRING
			exit 1
		}

		continue
	}

	# try to get libraries on Fedora
	which yum &>/dev/null && {
		$SUDO yum -y install gcc-c++ \
			make \
			libX11-devel \
			libXmu-devel \
			libXrender-devel \
			libXft-devel \
			freetype-devel \
			libpng-devel || {
			echo $ERROR_STRING
			exit 1
		}

		continue
	}

	# build on Gentoo
	which emerge &>/dev/null && {
		# assuming X libraries are installed already
		$SUDO emerge --noreplace libpng \
			libXrender \
			libXft \
			freetype || {
			echo $ERROR_STRING
			exit 1
		}

		continue
	}

	echo "error: sorry, your package management system is not supported."
	exit 1
done
