#!/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

# Find out which daemons to stop before the update
update_list=`pkg_version -o -L= | xargs -n1 pkg_info -qO`

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

# 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`"

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

# Install via portmaster
portmaster -adG

# 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 /usr/local/etc/rc.d/*; do
  $rc restart
done
