#!/bin/sh
#
# snapshot-run PROGRAM [ARGS]
# Create an Athena login snapshot, run PROGRAM within it, and clean up
# the snapshot.
#
# This script is run as the user who is logging in, usually as a wrapper
# around their Xsession or shell. You probably want to run reactivate
# immediately afterwards, as root.

set -e
cd /

addgroups="admin lpadmin adm fuse cdrom floppy audio video plugdev scanner dialout lp"
daemons="$(/usr/sbin/policy-rc.d --daemons)"

# Setup

session=$(schroot -c login -b)
sch() { schroot -r -c "$session" -- "$@"; }          # Run in the chroot
schq() { schroot -q -r -c "$session" -- "$@"; }      # Run in the chroot quietly
schr() { schroot -r -c "$session" -u root -- "$@"; } # Run in the chroot as root

for group in $addgroups; do
    schr getent group "$group" >/dev/null 2>&1 && schr adduser "$USER" "$group"
done

schr sed -i "/su-error/d" "/etc/pam.d/su.debathena"

schr touch /ClusterLogin

for daemon in $daemons; do
    schr invoke-rc.d "$daemon" start || [ $? = 100 ]
done

schr rm /etc/debian_chroot

# Deter people from thinking they can use /home as persistant storage
# by punting it
schr rm -rf /home

# Fix up mtab so that df and friends work correctly
schr sed -i "s| /var/lib/schroot/mount/${session}/| /|" /etc/mtab

# Run the session
#
# We wrap the target command in sudo because it runs initgroups(3)
# /after/ being chrooted, which puts users back in the groups we
# added them to

# Workaround for stupidity, see #928 for details
# Remove this once we're running pam-afs-session 2.4
# Run this inside the "set -e" block so it'll fail if necessary
echo "KRB5CCNAME=$KRB5CCNAME" >| /tmp/ticketenv

set +e

echo "$USER ALL=(ALL) ALL" | schr sh -c "cat >> /etc/sudoers"

cd
schroot -c "$session" -r -p -- sudo -E -u "$USER" -- "$@"
cd /

# Teardown

# Remove file from above.
# (This also gets nuked in reactivate, but be paranoid)
rm -f /tmp/ticketenv

for daemon in $daemons; do
    schr invoke-rc.d "$daemon" stop || [ $? = 100 ]
done

schroot -c "$session" -e
