#!/bin/bash
#
# Cleans up after a login snapshot to make the machine ready for the
# next login.
#
# This script may choose to reboot the machine in order to clear
# user processes or processes using the login snapshot, although
# that circumstance should be fairly rare.

print_processes_info() {
  echo "BEGIN PRINT_PROCESS_INFO"
  pstree -alcnpu
  ps eauxwww
  schroot --list -a
  mount
  LC_ALL=C lsof -b +c 0 -w
  echo "END PRINT_PROCESS_INFO"
}

set -e
exec >>/var/log/athena-reactivate 2>&1

# Stop any daemons that were specifically started inside the
# chroot
for daemon in $daemons; do
  invoke-rc.d $daemon restart || [ $? = 100 ]
done

# schroot has already attempted to kill everything inside the chroot,
# fairly thoroughly. Our job here is to determine if anything is stuck
# after a kill -9, and reboot.
for i in /var/lib/schroot/mount/*; do
  if mountpoint -q "$i"; then
    touch /var/run/reboot-required
    echo "rebooting due to active mountpoint $i"
    print_processes_info
    break
  fi
done
if [ -n "$USER" -a "$USER" != root ]; then
  if pgrep -u "$USER"; then
    echo "rebooting due to live user processes"
    print_processes_info
    touch /var/run/reboot-required
  fi
fi

# Cleanup our ticketenv hack
# Make sure nobody was evil
chattr -f -i /tmp/ticketenv || :
# If you made a directory and stored files there, too bad
rm -rf /tmp/ticketenv

# If either we or an updated package wanted to reboot, now is a
# perfectly good time to do so -- auto-update is inhibited during a
# login session.
if [ -e /var/run/reboot-required ]; then
  echo "Reboot initiated at $(date)"
  reboot
fi

# Trac: #749
service ntp stop
gettime -s time.mit.edu
service ntp start


# Yes, we want this here.  A reboot will take care of cleaning up
# /var/run anyway, and since dbus is essential to rebooting these
# days, we don't want to risk things magically getting spawned inside
# a crippled chroot
rm /var/run/debathena-inhibit-dbus-helper
