#!/bin/bash
# Copyright 2021 ylee@bodhilinux.com
#
# This file is part of apturl-saf
#
# "apturl"-saf is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 3 of the License, or (at
# your option) any later version.
#
# "apturl"-saf is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with "apturl"-saf; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

if ! hash synaptic-pkexec 2>/dev/null; then
	zenity "$OPTIONS" --error --text="Please install Synaptic package manager." --width=400 --title="apturl"
	exit 255
fi

if ! hash pkexec 2>/dev/null; then
	zenity "$OPTIONS" --error --text="Please install policykit-1." --width=400 --title="apturl"
	exit 255
fi

if [ -z "$*" ]; then
	zenity "$OPTIONS" --error --text="No arguments" --width=400 --title="apturl"
	exit 1
fi

apt_part="$(printf '%s' "$1" | cut -c1-4)"
if [ "$apt_part" != "apt:" ]; then
	zenity "$OPTIONS" --error --text="Invalid Url."
	exit 2
fi

pkg="$(printf '%s' "$1" | cut -c5-)"
if ! apt-cache show "$pkg" &>/dev/null; then
	zenity "$OPTIONS" --error --text="Could not find package '$pkg'" --width=400 --title="apturl"
	exit 3
fi

if ! zenity "$OPTIONS" --question --text="Do you wish to install $pkg?" --width=400 --title="apturl"; then
	exit 4
fi

if dpkg -s "$pkg" &>/dev/null; then
	if  ! dpkg -l | grep '^rc' | grep $pkg &>/dev/null; then
		zenity "$OPTIONS" --info --text="'$pkg' is already installed!" --width=400 --title="apturl"
		exit 5
	fi
fi

echo "installing $pkg..."

tmpfile=$(mktemp /tmp/tmp-XXXXXX)
chmod +r "$tmpfile"
trap 'rm -f -- "$tmpfile"' INT TERM HUP EXIT
: > "$tmpfile"

echo "$pkg install" >"$tmpfile"
if [ -z ${BODHI_APTURL+x} ]; then
	pkexec synaptic --hide-main-window --non-interactive --progress-str 'Please wait, this can take some time.' --finish-str 'Update is complete' --set-selections-file "$tmpfile"
else
	pkexec env DISPLAY="$DISPLAY" XAUTHORITY="$XAUTHORITY" apturl.synaptic "$tmpfile"
fi

if ! dpkg -s "$pkg" &> /dev/null; then
	# FIXME what to do if not installed?
	exit 6
fi
exit 0
