#!/bin/sh

complain() {
  logger -t "$(gethostname --fqdn)" -p user.notice "update: $*"
}

maybe_reboot() {
  if [ -f /var/run/reboot-required ]; then
    # A package wants us to reboot the machine.  Do so if no one is
    # logged in.  Be paranoid about stale utmp entries.
    ttys=$(w -h -s | awk '{print $2}')
    for tty in $ttys; do
      pids=$(ps --no-heading -j -t "$tty" 2>/dev/null \
             | awk '($1 == $3) {print $1}')
      if [ -n "$pids" ]; then
        return
      fi
    done
    # screen processes count as logins.
    if pgrep '^screen' > /dev/null; then
      return
    fi
    reboot
    exit
  fi
}

if [ 0 != "$(id -u)" ]; then
  echo "This script must be run as root." >&2
  exit 1
fi

# Avoid confusing the system by running two updates at once.
pidfile=/var/run/athena-update.pid
if [ -e $pidfile ]; then
  if ! kill -0 "$(cat $pidfile)" 2>/dev/null; then
    rm -f $pidfile
  fi
fi
(set -o noclobber; echo $$ > $pidfile) 2>/dev/null || exit

trap 'rm -f $pidfile' EXIT

# Make sure nothing expects input on stdin.
exec </dev/null

# Punt output while we figure out if there are updates to take.
exec >/dev/null 2>&1

# Allow hesiod cluster info to specify the debathena apt repository.
# (Will do nothing if debathena-clusterinfo isn't installed.)
[ -x /usr/sbin/save-cluster-info ] && /usr/sbin/save-cluster-info
cinfo=/var/run/athena-clusterinfo.sh
slist=/etc/apt/sources.list.d/debathena.list
if [ -r $cinfo -a -w $slist ]; then
  (. $cinfo;
   [ -n "$APT" ] && perl -pi.old -e 's|http://\S+|$ENV{"APT"}|e;' $slist)
fi

# Tell apt not to expect user input during package installation.
export DEBIAN_FRONTEND=noninteractive

# Update the aptitude cache.
if ! aptitude --quiet --assume-yes update; then
  complain "aptitude update failed"
  exit
fi

# Exit quietly (except for perhaps rebooting) if there are no upgrades
# to take.
pattern='^0 packages upgraded, 0 newly installed, 0 to remove'
if aptitude --simulate --assume-yes full-upgrade | grep -q "$pattern"; then
  maybe_reboot
  exit
fi

# Redirect further output to a log file.
exec >>/var/log/athena-update 2>&1

# Write a log header now and a footer at exit.
echo "-----"
echo "** Beginning Athena auto-update at $(date)"

finish() {
    echo "** Ending Athena auto-update at $(date)"
    echo "-----"
    echo
    rm -f $pidfile
    exit
}
trap finish EXIT

v() {
  echo "** Running:" "$@"
  "$@"
}

# Download packages first.
if ! v aptitude --quiet --assume-yes --download-only full-upgrade; then
  complain "download failed"
  exit
fi

# If the debathena-reactivate package is installed, call into the
# login snapshot script to create a root snapshot for the next update.
if [ -x /usr/sbin/athena-login-snapshot ]; then
  echo "** Creating root snapshot"
  /usr/sbin/athena-login-snapshot update-start
fi

# Perform the update.  In some corner cases, aptitude might decide
# that the best course of action is to remove the Debathena
# metapackage, so be paranoid about that.
v aptitude --quiet --assume-yes keep-all
v aptitude --quiet --assume-yes --download-only dist-upgrade
if result=$(aptitude -F "%p" search '~i!~VTARGET(^debathena-cluster$ | ^debathena-workstation$ | ^debathena-login$ | ^debathena-standard$ | ^openafs-modules-~D^linux-image-)')
  [ -n "$result" ]; then
  echo "** metapackages would be removed by the update, aborting:" $result
  v aptitude --quiet --assume-yes keep-all
  complain "metapackages would be removed by update:" $result
elif result=$(aptitude -F "%p" search '~b')
  [ -n "$result" ]; then
  echo "** packages would be broken by the update, aborting:" $result
  v aptitude --quiet --assume-yes keep-all
  complain "packages would be broken by update:" $result
else
  v aptitude --quiet --assume-yes install
fi

if [ -x /usr/sbin/athena-login-snapshot ]; then
  echo "** Cleaning up root snapshot"
  /usr/sbin/athena-login-snapshot update-end
fi

maybe_reboot
exit
