#!/bin/bash
#
#Copyright 2012 CurlyMo <development@xbian.org>
#
#This file is part of XBian - XBMC on the Raspberry Pi.
#
#XBian 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.
#
#XBian 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 XBian. If not, see <http://www.gnu.org/licenses/>

function getInternetFn() {
    ping -c 1 8.8.8.8 > /dev/null 2>&1 && return 0
    return 1
}

function getPackageCategoryListFn() {
	CATEGORIES=($(echo -e "$CONTENT" | sed -ne 's/\(Section: \)\(.*\)/\2/p' | sort | uniq | grep -v update));
}

function getAllPackagesFn() {
	IFS=$'\n' PACKAGES=($(echo -e "$CONTENT" | grep "^Package:" | grep -v "xbian-update" | sed 's/Package: \|xbian-package-//g' | sort | uniq));
}

function getPackagesFromCategoryFn() {
        NAME=$1;
        NAME=${NAME/\//\\\/};
        IFS=$'\n' PACKAGES=($(echo -e "$CONTENT" | grep -v "xbian-update" | awk -vRS='' "/Section: $NAME/"'{print $0"\n"}' | grep "Package:" | sed 's/Package: \|xbian-package-//g' | sort | uniq))
}

function getPackageStatusFn() {
	echo -e "$ALLPKGLST" | grep -wq "xbian-package-$1\|$1"
	return $((1-$?))
}

function getPackageStatusCountFn() {
	return $(echo -e "$ALLPKGLST" | grep -wcE "$1")
}

function updateAllPackagesListFn() {
        #ALLPKGLST=$(dpkg-query -W --showformat='${Package} %%${Origin}%% %%${Status}%%\n'  | grep -i '%%XBian%%' | grep -w installed%%);
        ALLPKGLST=$(dpkg-query -W --showformat='${Package} %%${Origin}%% %%${Status}%%\n' | grep -v "xbian-update" | grep -w installed%%);
}

#Gets the package information
# $1: Package name (without prefix xbian-package-)
function getPackageInformationFn() {
	NAME=$1;
	echo -e "$CONTENT" | grep -q "Package: xbian-package-$NAME" && PREFIX="xbian-package-" || PREFIX=''
	INFO=$(echo -e "$CONTENT" | awk -vRS='' "/Package:[A-Za-z -]+$PREFIX$NAME\n/"'{print $0"\n"}' | grep -v "xbian-update");
	IFS=$'\n' VERSIONS=($(echo -e "$INFO" | sed -ne 's/\(Version: \)\([0-9\.]\{1,\}\)/\2/p'));
	X=0; I=0
	for KEY in ${!VERSIONS[@]}; do
	        V=$(echo ${VERSIONS[$KEY]} | sed 's/~RC[0-9]-/-/g')
		if [[ "$V" > "$X" ]]; then
			X=$V;
			I=$KEY;
		fi
	done;
	PKGINFO=();
	INFO=$(echo -e "$INFO" | awk -vRS='' "/Version: $(echo $X | sed 's/+/[+]/g')/"'{ if ( ++hit == 1 ) {print $0"\n"} }' );
	PKGINFO[0]=$(echo -e "$INFO" | sed -ne 's/\(Package: \)\([A-Za-z0-9. -]\{1,\}\)/\2/p' | sort -r);
	PKGINFO[1]=${VERSIONS[$I]}
	PKGINFO[2]=$(($(echo -e "$INFO " | sed -ne 's/\(Installed-Size: \)\([0-9]\{1,\}\)/\2/p')*1024))
	PKGINFO[3]=$(echo -e "$INFO" | sed -ne 's/\(^Size: \)\([0-9]\{1,\}\)/\2/p');
	PKGINFO[4]=$(echo -e "$INFO" | sed -ne 's/\(Description: \)\([A-Za-z0-9\ ]\{1,\}\)/\2/p');
	PKGINFO[5]=$(echo -e "$INFO" | sed -ne 's/\(Depends: \)\([A-Za-z0-9\ ]\{1,\}\)/\2/p')
	IFS=$ORIGNALIFS;
}

#Installs a package
# $1: Simulate or not
# $2: Full package name
function installPackageFn() {
	cmd=$1
	shift
	NAME=$1;
	NAME=${NAME/xbian-package-/}
	NAME=$(echo $NAME | cut -f 1 -d"=");
	#if [ $(getPackageStatusFn $NAME; echo $?) -eq 1 ]; then
	#	return 1;
	if [ $cmd -eq 1 ]; then
		LC_ALL=C.UTF-8 eval apt-get install -s $@ &>/tmp/aptstatus
	elif [ $cmd -eq 0 ]; then
		LC_ALL=C.UTF-8 DEBIAN_FRONTEND=noninteractive eval apt-get install -y --allow-change-held-packages -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" $@ &>/tmp/aptstatus
	elif [ $cmd -eq 2 ]; then
		LC_ALL=C.UTF-8 DEBIAN_FRONTEND=noninteractive eval nohup apt-get install -y --allow-change-held-packages -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" $@ &>/tmp/aptstatus &
	fi
	# Returncode only correct on simulation (1) on real operation (0,2) probably useless
	getAptErrorCodeFn;
	return $?;
}

#Remove a package
# $1: Simulate or not
# $2: Full package name
function removePackageFn() {
	NAME=$2;
	NAME=${NAME/xbian-package-/}
	NAME=${NAME%=*}
	if [ $(getPackageStatusFn $NAME; echo $?) -eq 0 ]; then
		return 1;
	else
		if [ $1 -eq 1 ]; then
			LC_ALL=C.UTF-8 apt-get purge -s $2 &>/tmp/aptstatus

			if [ $(grep -c "is not installed, so not removed" /tmp/aptstatus) -eq 1 ]; then
				return 1;
			elif [ $(grep -c "essential package" /tmp/aptstatus) -eq 1 ]; then
				return 2;
			elif [ $(grep -c "Unable to locate" /tmp/aptstatus) -eq 1 ]; then
				return 3;
			else
				return 0;
			fi
		elif [ $1 -eq 0 ]; then
			LC_ALL=C.UTF-8 apt-get purge -y $2 &>/tmp/aptstatus
		elif [ $1 -eq 2 ]; then
			LC_ALL=C.UTF-8 nohup apt-get purge -y $2 &>/tmp/aptstatus &
		fi
	fi
}
