#!/bin/sh

complain() {
  logger -t "athena-auto-update" -p user.notice "$*"
  updstatus="failed"
  updmsg="$*"
}

save_success() {
  updstatus="ok"
  updmsg=$1
}

save_state() {
  rm -f $statfile
  echo "$updlast|$(date +"%s")|$updstatus|$updmsg" > $statfile
}  

maybe_reboot() {
  if [ "$SHOULD_REBOOT" = "no" ]; then
      return
  fi
  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
    save_state
    reboot
    exit
  fi
}

SHOULD_REBOOT="yes"
if [ "$1" = "-n" ]; then
    SHOULD_REBOOT="no"
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

if [ "$1" = "cron" ]; then
    case `date +"%H"` in
	0[2-6])
	    # 2 hrs
	    interval=7200
	    ;;
	*)
	    # 6 hrs
	    interval=21600
	    ;;
    esac
    if ! desync -t /var/run/athena-update.desync $interval; then
	exit 0
    fi
fi

statfile="/var/lib/athena-update-status"
updstatus="unknown"
updmsg=""
updlast=$(date +"%s")

# Get the last successful update
if [ -f $statfile ]; then
    updlast=$(awk -F\| '{print $1;}' $statfile)
fi

# 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
    save_state
    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

# Configure any unconfigured packages (Trac #407)
if ! v dpkg --configure -a; then
  complain "Failed to configure unconfigured packages."
  exit
fi  

# A recently configured package may want a reboot
save_success "Rebooted after dpkg --configure -a"
maybe_reboot

# 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!"
  save_success "No updates"
  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

APTITUDE_OPTS=
# On cluster machines, force the new conffile if there's a conflict
if dpkg-query --showformat '${Status}\n' -W "debathena-cluster" 2>/dev/null | grep -q ' installed$'; then
    APTITUDE_OPTS="-o Dpkg::Options::=--force-confnew"
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 $APTITUDE_OPTS --quiet --assume-yes install
  # Successful update, reset $updlast
  updlast=$(date +"%s")
  save_success "Successful update"
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
