#!/bin/sh

# UPGRADE.sh - shell script to provide an automated upgrade of all installed
#              packages for which an upgrade has been retrieved.
#
# 2005-09-25 Sylvain Robitaille: Start thinking about doing this via a
#                                Makefile, actually ...
# 2009-11-15 Sylvain Robitaille: allow for 64-bit Slackware; allow also for
#                                *.txz packages,

# CONFIGURE:
INSTALLED_PATH=/var/log/packages
SYSTEM_VERSION=`cat /etc/slackware-version |\
                   tr '[A-Z]' '[a-z]' |\
                   sed 's/\([1-9]*\.[0-9]*\)\(\.[0-9]*\)*$/\1/; s/ /-/g'`
# x86 64-bit?
if [ "`uname -m`" = "x86_64" ]; then
   # yes; we need to be sure the version string takes that into account:
   SYSTEM_VERSION=`echo ${SYSTEM_VERSION} |sed 's/slackware-/slackware64-/'`
else
   # not x86 64-bit; leave as is ...
   /bin/true
fi

SLACKWARE_VERSION=${1:-${SYSTEM_VERSION}}
DOWNLOADED_PATH=/local/var/slackware/${SLACKWARE_VERSION}
LISTING_FILE=${DOWNLOADED_PATH}/.listing
FTP_HOST=ftp-linux.cc.gatech.edu
FTP_PATH=pub/slackware/${SLACKWARE_VERSION}/patches/packages
GPG_HOME=${HOME}/.gnupg

do_upgrade () {
   opts="$*"
   # Of all the packages we have downloaded, for which we have an older
   # version installed, upgrade the package:
   if [ ${LISTING_FILE} -nt ${INSTALLED_PATH} ]; then
      for file in `find ${DOWNLOADED_PATH} -type f \
                                           -name "*.t[gx]z" \
                                           -cnewer ${INSTALLED_PATH}`; do
         gpg --homedir ${GPG_HOME} --verify ${file}.asc 1>/dev/null 2>&1 && \
         upgradepkg ${opts} ${file}
      done
   fi
}


if [ ! -d ${DOWNLOADED_PATH} -o ! -w ${DOWNLOADED_PATH} ]; then
    ls -ld ${DOWNLOADED_PATH}
fi

# If we're operating as root, upgrade to the newer packages,
# else retrieve new packages and report what would be upgraded:
case `whoami` in
   root)
      if [ "${SYSTEM_VERSION}" == "${SLACKWARE_VERSION}" ]; then
         mount -w -o remount /usr
         do_upgrade
         mount    -o remount /usr
      fi
   ;;
   *)
      #if [ ${INSTALLED_PATH} -nt ${LISTING_FILE} ]; then
         cd ${DOWNLOADED_PATH} && \
         wget -m -nd -np -nv ftp://${FTP_HOST}/${FTP_PATH}/.
      #fi
      if [ "${SYSTEM_VERSION}" == "${SLACKWARE_VERSION}" ]; then
         do_upgrade --dry-run
      fi
   ;;
esac

