#!/bin/sh

# +=======================================================================+
# || cipux_cleanup_class_shares.sh                                       ||
# ||                                                                     ||
# || Cleanup script to remove obsolete student accounts                  ||
# || from class shares which were removed via                            ||
# ||     cipux_task_client -t cipux_task_destroy_student_account -o $STUDENT
# || but still get listed in the class share with                        ||
# ||     cipux_task_client -t cipux_task_list_members_of_class_share -o $CLASSSHARE
# ||                                                                     ||
# || Syntax:                                                             ||
# ||   cipux_cleanup_class_shares.sh                                     ||
# ||                                                                     ||
# || Copyright (C) 2009 by Andreas Brand                                 ||
# ||                                                                     ||
# || License: GNU GPL version 2 or any later version.                    ||
# ||                                                                     ||
# +=======================================================================+
#
# $Id$
# $Revision$
# $HeadURL$
# $Date$
# $Source$

# abort on uncaught errors:
set -e

# change this if necessary:
CIPUX_HOME_BASE_DIRECTORY="/skole/tjener/home0/"

# 1. Go through all classes
# while handles share names containing white space correctly:
cipux_task_client -t cipux_task_list_class_shares | while read current_class
do
  # 2. Go through all members of specific share
  # ATTENTION: output is tab separated, so we must convert into newlines
  # so while can handle member names containing white space correctly:
  cipux_task_client -t cipux_task_list_members_of_class_share -o "${current_class}" | tr '\t' '\n' | while read current_member
  do
    # see if this member is a known login:
    if ! login_name=$(id -un "${current_member}"); then    
       echo "Member '${current_member}' of class share '${current_class}' doesn't exist anymore --> remove it"
       # 3. remove obsolete account:
       cipux_task_client -t cipux_task_remove_member_from_class_share -o "${current_class}" -x value="${current_member}"

       # remove the home directory as well:
       user_home_dir="${CIPUX_HOME_BASE_DIRECTORY}${current_member}"
       if [ -d "$user_home_dir" ]; then
         echo "Remove obsolete home directory '$user_home_dir' as well ..."
         rm -r "$user_home_dir"
       fi

    else
       echo "Member '${current_member}' of class share '${current_class}' exists (login name '${login_name}') --> keep it"
    fi

  done

done

