#!/bin/bash
#
#Copyright 2012 - 2017 CurlyMo, mk01 & mkreisl <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 updateAptMirrorsFn() {
	src="$(cat /etc/apt/sources.list /etc/apt/sources.list.d/*.list 2>/dev/null| grep '^deb.*xbian.*\|^mirror.*xbian.*'  | awk '{print $2}' | sort | uniq)"
	[ -z "$src" ] && URL=$APTBASE || URL=$src
	echo "$URL" | grep -q $APTBASE || URL="$APTBASE $URL"

	rm -f $BASEPATH/config/aptmirror.new
	for a in $URL; do    
	    a=$(echo $a | sed 's%mirror://%http://%')
	    a=${a%%/mirror.txt}; a=${a%%/}
	    wget --spider $a/mirror.txt >/dev/null 2>&1 || continue
	    wget -O - $a/mirror.txt >> $BASEPATH/config/aptmirror.new 2>/dev/null || continue
	    cat $BASEPATH/config/aptmirror.new | sort | uniq > $BASEPATH/config/aptmirror
	    return 0
	done
	return 1
}

function localPackageDBOutdatedFn() {
	if [ -f "/var/lib/apt/periodic/update-success-stamp" ]; then
		int=$(grep "APT::Periodic::Update-Package-Lists" /etc/apt/apt.conf.d/20auto-upgrades 2>/dev/null| grep -o "[0-9]*")
		[ -z "$int" -o "$int" -eq 0 ] && int=1440 || int=$((int*24*60))
		if [ -z "$(eval find /var/lib/apt/periodic/update-success-stamp -cmin -$int 2>/dev/null)" ]; then
			return 1;
		else
			return 0;
		fi
	else
		return 1;
	fi
}

function downloadPackageListFn() {
	test -n "$(find /var/lib/apt/periodic/package-success-stamp -cmin -10 2>/dev/null)" && return 1
	RETURN=1;
	if [ -f "$BASEPATH/config/aptmirror" ]; then
		IFS=$'\n';
		MIRRORS=($(cat $BASEPATH/config/aptmirror));
		for MIRROR in ${MIRRORS[@]}; do
			MIRROR=${MIRROR%%/}
			RETURN=0; rm /tmp/sources 2>/dev/null
			IFS=$'\ ';
			rm -f $BASEPATH/config/pkglist.new
			err=0
			cat /etc/apt/sources.list /etc/apt/sources.list.d/*.list 2>/dev/null| grep '^deb.*xbian.*\|^mirror.*xbian.*' | awk '{print "dists/"$3"/{"$4","$5","$6","$7"}/binary-armhf/Packages"}' | \
			while read m; do
			    m=$(eval echo $m)
			    for n in $m; do
				n=$(echo $MIRROR/$n | sed 's%mirror://%http://%')
				n=${n%%/mirror.txt}; n=${n%%/}
				if [ $(wget --spider $n >/dev/null 1>/dev/null 2>/dev/null; echo $?) -eq 0 ]; then
				    wget -O - $n >> $BASEPATH/config/pkglist.new 2>/dev/null
				    err=$((err + $?))
				fi
			    done
			done
			[ $err -ne 0 ] || { mv $BASEPATH/config/pkglist.new $BASEPATH/config/pkglist; touch /var/lib/apt/periodic/package-success-stamp; break; }
		done
		IFS=$ORIGINALIFS;
	fi
	return $err
}

#Retrieves the package version
# $1: Full name of the package
function getPackageVersionFn() {
	dpkg-query -W -f='${Version}\n' "$1" 2>/dev/null
}

function updateAptFn() {
        apt-get -q clean
        if [ "$1" = speak ]; then
                apt-get update --allow-releaseinfo-change 2>&1 | tee /tmp/aptstatus
        else
                apt-get update --allow-releaseinfo-change 2>&1 >/tmp/aptstatus
        fi
        rm -f /tmp/aptupdates
        touch /var/lib/apt/periodic/update-stamp
        touch /var/lib/apt/periodic/update-success-stamp
}

function getAllPackagesForInstallFn() {
	ALLPACKAGES=$(cat /tmp/aptstatus | awk '/upgraded:/ {flag=1;next} /upgraded/{flag=0} flag{print}' | sed 's/ *$//g' | sed 's/^ *//g' | sed ':a;N;$!ba;s/\n/ /g');
}

function getAptErrorCodeFn() {
	if [ $(grep -c "already the newest version" /tmp/aptstatus) -eq 1 ]; then
		return 1;
	elif [ $(grep -c "was not found" /tmp/aptstatus) -eq 1 ]; then
		return 2;
	elif [ $(grep -c "Unable to locate package" /tmp/aptstatus) -eq 1 ]; then
		return 3;
	elif [ $(grep -c "DOWNGRADED" /tmp/aptstatus) -eq 1 ]; then
		return 4;
	elif [ $(grep -c -i "size mismatch" /tmp/aptstatus) -eq 1 ]; then
		return 5;
	elif [ $(grep -c -i "returned an error code" /tmp/aptstatus) -eq 1 ]; then
		return 6;
	elif [ $(grep -c -i "impossible situation" /tmp/aptstatus) -eq 1 ]; then
		return 6;
	else
		return 0;
	fi
}
