#!/bin/bash
#
# by: Forrest (20101203)
#
# Setup script for the process lab
# This script is to be installed and run on serverX.example.com
# Output is logged to syslog

# Set environment and declare global variables
. /usr/local/lib/labtool.shlib
trap on_exit EXIT
LOG_FACILITY=local0
LOG_PRIORITY=info
LOG_TAG=processes-test
DEBUG=false
ERROR_MESSAGE="Error running script. Contact your instructor if you continue to see this message."
PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin
userInput="no"
set -o pipefail
stationNum="$(hostname -s | grep -o "[0-9]*")"
DU_FILE=/home/student/Desktop/usr-directory.txt
DF_FILE=/home/student/Desktop/least-free-space-filesystem.txt

# Check to make sure we are running as root
check_root

# Check to make sure we are running on the correct host
check_host "desktop"

# Prompt the user before we make any changes to the system
cat <<EOL

*** NOTICE ***
This script will reset vserver to setup the excercise.
EOL
confirm
echo
echo -n "Setting up, one moment please... "

# Reset vserver
(/usr/local/sbin/lab-resetvm 2>&1 | log) || exit

# Configure vserver to use the classroom network
(gls-vserver-network --classroom 2>&1 | log) || exit

# Wait for ssh to become available then create and install sshkey on vserver
wait_tcp_port server${stationNum}.example.com 22
push_sshkey server${stationNum}.example.com
sshKey="/root/.ssh/.labtoolkey"

# Run the processes
ssh -i $sshKey root@server${stationNum}.example.com 'at -f /usr/local/sbin/monitor-test now'
# Create the df file
ssh -i $sshKey root@server${stationNum}.example.com "mkdir -p /home/student/Desktop ; df | cut -c 41-80 | grep / | awk '{print \$3}' > $DF_FILE ; chown -R student:student /home/student"
# Create the du file
ssh -i $sshKey root@server${stationNum}.example.com "mkdir -p /home/student/Desktop ; du -sm /usr/* | awk '{print \$2}' > $DU_FILE ; chown -R student:student /home/student"

echo "done!"

exit 0
