#!/bin/bash

set -o nounset

if [ "$EUID" -ne 0 ]
then
	echo "Please run as root"
	echo "E.g.:"
	echo "$ sudo $0"
	exit 1
fi

if [ ! -f ./bin/GitWorks ]; then
	echo "Error, script needs to run from root package folder." 1>&2
	exit 1
fi

for dir in applications icons; do
	if ! mkdir -p "/usr/local/share/$dir"; then
		echo "Error, no write access to /usr/local/share/$dir" 1>&2
		exit 1
	fi
done

if [ -d "/opt/GitWorks" ]; then
	echo "There are already files underneath /opt/GitWorks"
	echo -n "Should we delete them an continue? (y/N) "
	read answer
	case "$answer" in
		y*|Y*)
			rm -rf /opt/GitWorks
			;;
		*)
			echo "Aborted."
			exit 1
			;;
	esac
fi
mkdir /opt/GitWorks || exit 1

cp -r share bin lib plugins qml /opt/GitWorks/ || exit 1

for link in bin/GitWorks \
	    share/applications/GitWorks.desktop \
	    share/icons/GitWorks.svg \
	    share/icons/GitWorks.png
do
	target="/usr/local/$link"
	if [ ! -L "$target" ]; then
		ln -s /opt/GitWorks/$link $target ||
			exit 1
	fi
done

echo "Installation of GitWorks successful"
