#!/bin/sh
#
# Unattended FreeBSD Ports upgrade cycle, please note that starting and stopping
# of services is taken care of in the pkgtools.conf
#
# Rick van der Zwet <info@rickvanderzwet.nl>
#
PATH=$PATH:/usr/local/sbin:/usr/local/bin
WC=`cd $(dirname $0); pwd -P`

if [  `id -u` -ne 0 ]; then
  echo "Root only!" 1>&2
  exit 1
fi

# Make sure we always using the latest version
svn up --non-interactive `dirname $0` | grep '^[A-Z] ' && {
  sh $0
  exit 0
}

portmaster --version 1>/dev/null 2>/dev/null || make -C /usr/ports/ports-mgmt/portmaster BATCH=yes install clean

# Fetch the latest details and provide listing of packages to be updated
portsnap fetch update || exit 1

echo "# Find out which packages to update"
update_list=`pkg_version -o -L= | xargs -n1 pkg_info -qO`

if [ -z "$update_list" ]; then
  echo "Everything is up2date"
  exit 0
fi

echo "# Find the rc.d/* entries affected"
for pkg in $update_list; do
  rc_d="$rc_d `pkg_info -qL $pkg $(pkg_info -qR $pkg) | grep -F '/rc.d/'`"
done
rc_d="`echo $rc_d | xargs -n1 | sort -u`"

echo "# Going to update the following packages:"
echo $update_list | xargs -n1 echo "# - "
echo "# The following daemons will not be available:"
for rc in $rc_d; do
  echo "# - $rc (`$rc status 2>&1 | grep -v -e '^Usage:' -e 'directive' -e '^Cannot'`)"
done
echo -n "# Do you like to update the packages: (y|n) [y]: "; read INPUT
case $INPUT in
  ''|y) ;;
  [yY][eE][sS]) ;;
  *) 
    echo "Canceled by user!"; exit 1
  ;;
esac

# Stop the daemons affected
for rc in $rc_d; do
  $rc stop
done

# Install via portmaster
portmaster --no-confirm -yadG

# Just to be sure try to start all port daemons again (this will make sure the
# already updated ones are also started nicely again).
for rc in `rcorder /usr/local/etc/rc.d/* 2>/dev/null`; do
  $rc restart
done
