#========================================================================
#
# PROGRAM FUNCTIONS
#

# Clean-up tmp and lock files
#
function cleanup() {
	echo
	if [ "$DELALL" = "1" ] && [ "$NAMEPKG" != "" ]; then
		rm $TEMP/$NAMEPKG &>/dev/null
	fi		
	( rm -f /var/lock/slackpkg.$$ && \
	  rm -f /tmp/FILELIST.TXT /tmp/*MANIFEST* /tmp/*PACKAGES.TXT \
	  /tmp/tmplist /tmp/blacklist.* /var/run/slackpkg.$$ ) &>/dev/null
	exit
}
trap 'cleanup' 2 14 15 		# trap CTRL+C and kill

# Got the name of a package, without version-arch-release data
#
function cutpkg() {
	echo ${1/.tgz/} | awk -F- 'OFS="-" { 
				if ( NF > 3 ) { 
					NF=NF-3
					print $0 
				} else {
					print $0
				}
			}'
}

# Show the slackpkg usage
#
function usage() {
	echo -e "\
slackpkg - version $VERSION\n\
\nUsage: \tslackpkg update [gpg]\t\tdownload and update files and 
\t\t\t\t\tpackage indexes
\tslackpkg install package\tdownload and install packages 
\tslackpkg upgrade package\tdownload and upgrade packages
\tslackpkg reinstall package\tsame as install, but for packages 
\t\t\t\t\talready installed
\tslackpkg blacklist\t\tBlacklist a package. Blacklisted
\t\t\t\t\tpackages cannot be upgraded, installed
\t\t\t\t\tor reinstalled by slackpkg
\tslackpkg download\t\tJust download (do not install) a package
\tslackpkg info package\t\tShow package information 
\t\t\t\t\t(works with only ONE package)
\tslackpkg search file\t\tSearch for a specific file in the
\t\t\t\t\tentire package collection
\nYou can see more information about slackpkg usage and some examples
in slackpkg's manpage. You can use partial package names (such as xfree86
instead xfree86-devel, xfree86-docs, etc), or even slackware series
(such as "n","ap","xap",etc) when searching for packages.
"
	cleanup
}

# Verify if the package was corrupted by checking md5sum
#
function checkpkg() {
	MD5ORIGINAL=`grep "${NAMEPKG}$" ${CONF}/CHECKSUMS.md5| cut -f1 -d \ `
	MD5DOWNLOAD=`md5sum ${TEMP}/${1} | cut -f1 -d \ `
	if [ "$MD5ORIGINAL" = "$MD5DOWNLOAD" ]; then
		echo 1 
	else
		echo 0 
	fi
}

function checkgpg() {
	gpg --verify $TEMP/${1}.asc $TEMP/$1 2>/dev/null && echo "1" || echo "0"
}


# Function to make install/reinstall/upgrade lists
#
function makelist() {
	echo -n "Looking for $(echo $1 | tr -d '\\') in package list. Please, wait... "
	ls -1 /var/log/packages > ${CONF}/tmplist


	for i in `egrep /${1} ${CONF}/pkglist | awk -F/ '{ print $NF }'`; do
		BASENAME=`cutpkg $i`

		# That lines above choose de package with the higher priority
		#
		TEST=`grep -e "^\./${FIRST}\(\|/.*\)/${BASENAME}-[^-]\+-\(noarch\|i[3456]86\)" ${CONF}/pkglist` || \
		TEST=`grep -e "^\./${SECOND}\(\|/.*\)/${BASENAME}-[^-]\+-\(noarch\|i[3456]86\)" ${CONF}/pkglist` || \
		TEST=`grep -e "^\./${THIRD}\(\|/.*\)/${BASENAME}-[^-]\+-\(noarch\|i[3456]86\)" ${CONF}/pkglist` || \
		TEST=`grep -e "^\./${FOURTH}\(\|/.*\)/${BASENAME}-[^-]\+-\(noarch\|i[3456]86\)" ${CONF}/pkglist` || continue 

		PKGNAME=`echo $TEST | awk -F/ '{ print $NF }'`
		BASENAME=`cutpkg $PKGNAME`
		
		# That two will check if the package are in blacklist or
		# if it's already installed
		egrep -qx "${BASENAME}" ${CONF}/blacklist && continue 
		PKGFOUND=`grep -e "^${BASENAME}-[^-]\+-\(noarch\|i[3456]86\)" ${CONF}/tmplist`.tgz
		
		# Based in PKGFOUND info, put the package in the right
		# list.
		#
		if [ "$PKGFOUND" = "$PKGNAME" ]; then
			REINSTALLPKG="$REINSTALLPKG $PKGNAME"
		elif [ "$PKGFOUND" = ".tgz" ]; then
			INSTALLPKG="$INSTALLPKG $PKGNAME"
		else
			UPGRADEPKG="$UPGRADEPKG $PKGNAME"
		fi
	done
	REINSTALLPKG=`echo -e $REINSTALLPKG | tr \  "\n" |sort|uniq`
	INSTALLPKG=`echo -e $INSTALLPKG | tr \  "\n" |sort|uniq`
	UPGRADEPKG=`echo -e $UPGRADEPKG | tr \  "\n" |sort|uniq`
	echo -e "DONE\n"
}

# Function to count total of packages
#
function countpkg() {
	COUNTPKG=`echo -e "$1" | wc -w`
	if [ "$COUNTPKG" != "0" ]; then
		echo -e "Total of package(s): $COUNTPKG\n"
	fi
}

# Show the lists and asks if the user want to proceed with that action
#
function showlist() {
	for i in $1; do echo $i; done | more 
	echo
	countpkg "$1"
	echo -e "Do you wish to $2 selected packages (Y/n)? \c"; read ANSWER
	if [ "$ANSWER" = "Y" -o "$ANSWER" = "y" ] || [ "$ANSWER" = "" ]; then
		continue
	else
		cleanup
	fi
}

function getfile() {
        if [ "$LOCAL" = "1" ]; then
                echo -e "\t\t\tCopying $1..."
                cp ${SOURCE}$1 $2 2>/dev/null
        else
                echo -e "\t\t\tDownloading $1..."
                wget $WGETFLAGS ${SOURCE}$1 -O $2
        fi
}                                                       

# Function to download the correct package and many "checks"
#
function getpkg() {
	ISOK="1"
	NAMEPKG=`grep -m 1 "/$1$" ${CONF}/pkglist`
	
	if [ "`ls ${TEMP}/$1 2>/dev/null`" = "" ]; then
		echo -e "\nPackage: $1"
		# Check if the mirror are local, if is local, copy files 
		# to $TEMP else, download packages from remote host and 
		# put then in $TEMP
		#
		if [ "$LOCAL" = "1" ]; then 
                	echo -e "\tCopying $1..."
			cp ${SOURCE}${NAMEPKG} $TEMP
			cp ${SOURCE}${NAMEPKG}.asc $TEMP
		else
                	echo -e "\tDownloading $1..."
			wget $WGETFLAGS -P $TEMP -nd ${SOURCE}${NAMEPKG}
			wget $WGETFLAGS -P $TEMP -nd ${SOURCE}${NAMEPKG}.asc
		fi
	else
		echo -e "\tPackage $1 is already in cache, not downloading" 
	fi

	# If MD5SUM checks are enabled in slackpkg.conf, check the
	# packages md5sum to detect if they are corrupt or not
	#
	if [ "$CHECKPKG" = "1" ]; then
		ISOK=`checkpkg $1`
		[ "$ISOK" = "0" ] && ERROR="md5sum"
	fi

	# Check the package against its .asc. If you don't like this
	# disable GPG checking in /etc/slackpkg/slackpkg.conf
	#
	if [ "$NOGPG" != "1" ]; then
		ISOK=`checkgpg $1`
		[ "$ISOK" = "0" ] && ERROR="gpg"
	fi

	if [ "$ISOK" = "1" ]; then
		case $2 in
			installpkg)
				echo -e "\tInstalling ${1/.tgz/}..."
			;;
			upgradepkg)
				echo -e "\tUpgrading ${1/.tgz/}..."
			;;
			*)
				echo -e "\c"
			;;
		esac	
		( cd $TEMP && $2 $1 ) 
	else
		rm $TEMP/$1 2>/dev/null
		echo -e "\tERROR - Package not installed! $ERROR error!" 
	fi

	# If DELALL is checked, all downloaded files will be erased
	# after installed/upgraded/reinstalled
	#
	if [ "$DELALL" = "1" ]; then
		rm $TEMP/$1 $TEMP/${1}.asc 2>/dev/null
	fi		
}
