#! /bin/bash

usage() {
    echo "Usage: $0 userdel [options] LOGIN" 1>&2;
    echo "Options:"
    echo "    -f                           force removal of files,"
    echo "                                 even if not owned by user"
    echo "    -h                           display this help message and exit"
    echo "    -r                           remove home directory and mail spool"
    echo "    -Z                           remove SELinux user from SELinux user mapping"
    exit 1;
}

while getopts ":u:l:rfh" o; do
    case "${o}" in
#        Z)
#            u=${OPTARG}
#            ;;
        Z)
            Z='yes'
            ;;
        r)
            r='yes'
            ;;
        f)
            f='yes'
            ;;
        h)
            usage
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [[ $1 == '' ]];then
  usage
fi

lg=$1;shift
ID=`id -u -n ${lg} | xargs`
if [[ ${ID} != "${lg}" ]]; then
echo ${ID}
exit 1
fi

opt_r=""
if [[ "${r}" == "yes" ]];then
opt_r="-r"
fi

opt_f=""
if [[ "${f}" == "yes" ]];then
opt_f="-f"
fi

opt_Z=""
if [[ "${Z}" == "yes" ]];then
opt_Z="-Z"
fi

opt=$opt_r" "$opt_f" "$lg
##echo "opt: "$opt

home_dir=$(cat /etc/passwd | grep /$lg/ | cut -f6 -d":" | cut -f1 -d".")
us='/'$lg'/'
for var in $(cat /proc/mounts | grep ${us} | awk '{print $2}' | xargs)
do
  ##echo "Object: "$var
  /usr/bin/umount -l $var &>/dev/null
  /usr/bin/umount -f $var &>/dev/null
done

/sbin/userdel2 ${opt}
##echo "home: "$home_dir
if [[ ! -z $home_dir && $home_dir != "/" && $home_dir != "/bin" && $r == "yes" ]];then
    rm -rf $home_dir
    echo "User successfully removed"
fi

exit 0

