#!/bin/bash

# msgUsage: show a usage message and exit
msgUsage() {
  echo "Usage: $(basename $0) <past-dir> <current-dir>"
  echo "Where 'past-dir' and 'current-dir' are directories with all released packages"
  exit 0
}

# msgError: show a error message and exit
msgError() {
  echo "Error, $@" 2>&1
  exit 1
}

TMPDIR="$(mktemp -d)"

[ $# -lt 2 ] && msgUsage
[ ! -d $1 ] && msgError "$1 is not a directory"
[ ! -d $2 ] && msgError "$2 is not a directory"

PAST_DIR="$(cd $1; pwd)"
CURRENT_DIR="$(cd $2; pwd)"

find $PAST_DIR -type f -name '*.pkg.tar.*' -exec basename {} \; | sort | sed -e 's|#| |' -e 's|.pkg.*||' > $TMPDIR/past_packages
find $CURRENT_DIR -type f -name '*.pkg.tar.*' -exec basename {} \; | sort | sed -e 's|#| |' -e 's|.pkg.*||' > $TMPDIR/current_packages

# to know if package is removed/added/keep
PKG_STATUS=""

# show a list of updated packages
echo "* Updated packages"
while read past_pkg_name past_pkg_version_and_release; do
	while read current_pkg_name current_pkg_version_and_release; do
		if [ "$past_pkg_name" != "$current_pkg_name" ]; then
			continue
		else
			if [ "$past_pkg_version_and_release" != "$current_pkg_version_and_release" ]; then
				printf "%-20s %s\n" $past_pkg_name "$past_pkg_version_and_release -> $current_pkg_version_and_release"
			fi
			PKG_STATUS="KEEP"
		fi
	done < $TMPDIR/current_packages
	# after browse all current packages if someone is removed then
	if [ "$PKG_STATUS" != "KEEP" ]; then
		REMOVED_PACKAGES="$REMOVED_PACKAGES $past_pkg_name"
	fi
	# clean PKG_STATUS variable
	PKG_STATUS=""
done < $TMPDIR/past_packages

# show a list of new packages
echo
echo "* New packages"
while read current_pkg_name current_pkg_version_and_release; do
	found=0
	while read past_pkg_name past_pkg_version_and_release; do
		if [ "$current_pkg_name" == "$past_pkg_name" ]; then
			found=1
		fi
	done < $TMPDIR/past_packages
	if [ $found -eq 0 ]; then
		printf "%-20s %s\n" $current_pkg_name $current_pkg_version_and_release
	fi
	found=0
done < $TMPDIR/current_packages

# show a list of removed pacakges
echo
echo "* Removed Packages"
for P in $REMOVED_PACKAGES; do echo "$P"; done

sudo rm -rf $TMPDIR

# End of file
