#!/bin/sh
# FreeBSD system upgade script
#
# Licence: BSDLike - http://rickvanderzwet.nl/LICENSE
# Rick van der Zwet <info@rickvanderzwet.nl>

. /etc/rc.subr

ask_question() {
  QUESTION=$1
  DEFAULT=$2
  echo -n "$QUESTION? [$DEFAULT]: "; read INPUT
  INPUT=${INPUT:-"${DEFAULT}"}
  checkyesno INPUT || return 1 && return 0

}


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

DIRNAME=`dirname $0`
BATCH=${BATCH-""}

# Get list of rc.d marked for updates
RC_FILES=`$DIRNAME/port-list.sh`

# Update port tree
echo "# Updating portstree ..."
portsnap update > /dev/null

# Update ports listing
echo "# Checking ports which needs updating ..."
NEWPORTS=`pkg_version -qL=`

if [ -z "$NEWPORTS" ]; then
  echo "# System up2date"
  exit 0
fi

#
# Update ports
if [ -z "$BATCH" ]; then
  # Make sure we have read the (new) UPDATING announcements
  # Use ls to display the last motification time of the directories in
  # /var/db/pkg and assume that is the last time the user read the 
  # UPDATING file
  LAST_UPDATED=`ls -rtlD '%Y%m%d' /var/db/pkg/ | awk 'END{print $6}'`

  # Find new entries
  TMPFILE=`mktemp -t $(basename $0).XXX`
  awk -F: -v last=$LAST_UPDATED '{if (match($0,"^[0-9]+:$") && $1 < last) {exit}; print $0}' /usr/ports/UPDATING > $TMPFILE

  echo "# Show new /usr/ports/UPDATING entries (starting from $LAST_UPDATED) ..."
  if [`cat $TMPFILE | wc -l` -eq 7 ]; then
    echo "## No new entries found"
  else
   cat $TMPFILE
  fi
  rm $TMPFILE
  
  # agree to the terms of the game
  echo $NEWPORTS
  ask_question "Do you like to upgrade the affected ports" "no" || exit 1

  #
  # Stop daemons
  if [ -n "$RC_FILES" ]; then
    echo $RC_FILES
    ask_question "Do you like to stop your deamons" "yes" || exit
    for RC_FILE in $RC_FILES; do
      $RC_FILE stop
    done
  fi
fi
portupgrade -r -mBATCH=yes -a $NEWPORTS

#
# Restart daemons
if [ -n "$RC_FILES" ]; then
  echo $RC_FILES
  ask_question "Do you like to restart your deamons" "yes" || exit
  for RC_FILE in $RC_FILES; do
    $RC_FILE restart 
  done
fi
