#!/bin/sh

complain() {
  logger -t "$(hostname --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

# Don't run updates during a cluster login.
if [ -e /var/run/athena-login ]; then
  exit 0
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

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

# Write a log header now and a footer at exit.
# Also write a target for cluster's /etc/nologin symlink.
echo "-----"
echo "** Beginning Athena auto-update at $(date)"

cat > /var/run/athena-nologin << NOLOGIN
This system is currently taking software updates.
Please log in to a different system.
NOLOGIN

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

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


# Allow hesiod cluster info to specify the debathena apt release.
# (Will do nothing if debathena-clusterinfo isn't installed.)
[ -x /usr/sbin/save-cluster-info ] && v /usr/sbin/save-cluster-info
cinfo=/var/run/athena-clusterinfo.sh
slist=/etc/apt/sources.list.d/debathena.clusterinfo.list
if [ -r "$cinfo" ] && ( [ ! -e "$slist" ] || [ -w "$slist" ] ); then
  echo "** Updating debathena.clusterinfo.list"
  [ -e "$slist" ] && rm "$slist"
  dsource="$(egrep -h '^deb(-src)? http://debathena\.mit\.edu/apt ' /etc/apt/sources.list /etc/apt/sources.list.d/*.list 2>/dev/null | sort -u)"
  if [ -n "$dsource" ]; then
    (. $cinfo
     echo "# This file is automatically updated by debathena-auto-update"
     echo "# based on your Hesiod cluster information. If you want to"
     echo "# make changes, do so in another file."
     echo
     case $APT_RELEASE in
       production)  ;;
       proposed)    echo "$dsource" | awk '$3 !~ /-/ {$3 = $3 "-proposed"; print}' ;;
       development) echo "$dsource" | awk '$3 != /-/ {$3 = $3 "-proposed"; print}'
                    echo "$dsource" | awk '$3 != /-/ {$3 = $3 "-development"; print}' ;;
     esac
    ) > $slist
  else
    echo "Never mind, I can't figure out which sources.list line is Debathena's"
  fi
else
  echo "** Skipping update of debathena.clusterinfo.list"
fi

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

# Update the aptitude cache.
if ! v 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 v aptitude --simulate --assume-yes full-upgrade | grep -q "$pattern"; then
  echo "Nothing to do!"
  maybe_reboot
  exit
fi

# 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

# Finally, update the apt-file cache
v apt-file update

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

maybe_reboot
exit
