#!/bin/bash
# xopt-get - xPUD package manager v0.1

function usage {
	echo "Usage: 
 xopt-get <option> <path/url> - xPUD package manager
Installs xPUD packages from local devices and internet.

Options:
	install		Installs application
	remove		Remove application
	help		Display this help

For further informations please refer to README file."
}

function die {
	echo $1
	notify-send "xopt-get error" "$1" -i /usr/share/plate/chrome/content/image/cancel.png
	exit 1
}

function install {
	# check if path/url was specified
	if [ -z $1 ]; then
				echo "Path/URL missing."
			 exit
	fi
	echo "Starting installation of $1"
	dir=$(mktemp -d)
	cd $dir
	# check if url was given
	if [[ $1 =~ "://" ]]; then
		APP_NAME="xpud-app.tar.bz2"
		echo "Downloading package"
		wget $1 -O $APP_NAME || die "Download failed."
	else
		APP_NAME=$1
		echo "Package is local"
	fi
	# extract package
	echo "Extracting $APPNAME"
	tar xjvf $APP_NAME -C / || die "Unable to unpack package."
	# execute post-install script
	xterm -e /xinstall.sh || die "Error executing post-install script."
	# cleanup
	rm -rf /$dir
	rm /xinstall.sh
	echo "Installation complete"
	# TODO: show installed application name and icon
	notify-send 'Application installed' 'install success' -i /usr/share/plate/chrome/content/image/kthememgr.png
}

if [ -z $1 ]; then
	usage
else
	
	case $1 in
		install)
			install $2
			;;
		remove)
			echo "not implemented, yet"
			;;
		help|usage)
			usage
			;;
		*)
			echo "[xopt-get] $1: Unknown command, type 'xopt-get help' for a list of available commands."
			;;
	esac 
fi
