#!/bin/dash
# ROX right-click "install package" tool
# jamesbond 2018 - GPLv3 license
#
# $1 - package to be installed.
#
# Note: This is not a mass-installation tool, it can only install one package at a time
#       Use installpkg/upgradepkg for multiple installation. Or better yet, use slapt-get.
#

### configuration
PKG_DB_DIR=/var/log/packages
APPTITLE="Install Package"

### helper

# $1-msg, $2-title
msg() {
	[ $XPID ] && kill $XPID
	Xdialog --no-buttons --title "$2" -infobox "$1" 0 0 1000000 &
	XPID=$!
}

# $1-msg
msgbox() {
	[ $XPID ] && kill $XPID
	XPID=
	Xdialog -title "$APPTITLE" -infobox "$1" 0 0 10000
}

# $1-msg
yesno() {
	Xdialog --title "$APPTITLE" --yesno "$1" 0 0
}


####### main #######
[ $(id -u) -ne 0 ] && exec gtksu "Install Package ${1##*/}" "$0" "$@"

# 1. find pkgname
filename=${1##*/}
extension=${filename##*.}
[ "$extension" = "$filename" ] && extension=

fullpkgname=${filename%.$extension}
part=${filename#*-[0-9]}
pkgname=${filename%-[0-9]${part}}

# 2. Is package already installed?
echo "$ROOT$PKG_DB_DIR/$fullpkgname"
if [ -f "$ROOT$PKG_DB_DIR/$fullpkgname" ]; then
	yesno "${filename} is already installed. Re-install?" \
	&& install_cmd="upgradepkg --reinstall" || exit

else
	# 3. is another version of the package already installed?
	oldpkg=$(ls $ROOT$PKG_DB_DIR/$pkgname-[0-9]* 2> /dev/null)

	install_cmd=installpkg # by default is install
	if [ "$oldpkg" ]; then
		yesno "An older version of ${pkgname} exist.
		Remove old version  before installing this package?
		If you choose No, the result can be unpredictable." \
		&& install_cmd=upgradepkg
	fi	
fi

# 4. Actual installation
if yesno "Are you sure you want to install ${filename}?"; then 	
	msg "Installing ${filename}, please wait ..." "Installing"
	if $install_cmd "$1"; then
		msgbox "${filename} installed successfully."
	else
		msgbox "${filename} failed to install."
	fi
fi
