#!/bin/bash
#
# by: Brian Butler (20100902)
#
# Grading script for the samba 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
trap cleanup TERM
LOG_FACILITY=local0
LOG_PRIORITY=info
LOG_TAG=sambaLab
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

# Define cleanup function
function cleanup {
    log "Beginning cleanup..."
    (smbpasswd -x schoof 2>&1 | log)
    (userdel -r schoof 2>&1 | log)
    log "Cleanup Completed"
# Handle grading fails
    if [ "$1" = "fail" ]; then
        ERROR_MESSAGE="FAILED."
        exit 1
    else
        exit 0
    fi
}

# Check to make sure we are running as root
check_root

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

# Check for required packages
PACKAGES=( samba samba-client )
check_packages

# Check that \\hostname\school is shared from samba
echo
echo -n 'Checking \\$(hostname)\school is shared... '
(smbclient -L $(hostname) -N 2>&1 | grep school 2>&1 | log) || cleanup "fail"
echo "PASSED."

# Check that members of the group 'greenred' can access the share
echo
echo -n "Checking that the 'greenred' group can access \\\\$(hostname)\\school... "
(grep 'greenred' /etc/group &> /dev/null) || cleanup "fail"
(useradd -G greenred schoof 2>&1 | log) || cleanup
(echo 'grading' | passwd --stdin schoof 2>&1 | log) || cleanup
(echo 'grading' | tee - | smbpasswd -s -a schoof 2>&1 | log) || cleanup
(smbclient -U schoof%grading //$(hostname)/school -c pwd 2>&1 | log) || cleanup "fail"
echo "PASSED."

# Check that printers are not shared by samba
echo
echo -n "Checking that samba is not sharing printers... "
(grep '^ *[^;#]*load printers = yes\|^ *[^;#]*printable = yes' /etc/samba/smb.conf 2>&1 | log) && cleanup "fail"
echo "PASSED."
echo
echo "Lab Successfully Completed!"
cleanup
