#!/bin/bash

# The code which takes input from the user is borrowed from the script
# superadduser.

# Command line options #
# Will remove the user "black" from group portage
# ./superdeluser black portage 
# Will remove the user "black" from the system
# ./superdeluser black
# Will ask for the user name and then remove him/her from the system
# ./superdeluser 

# ALL THIS SHOULD BE SOURCED FROM SOME CONFIGURATION FILE 
# -------------------------------------------------------
# Path to files #
# Later it should be /etc/passwd but for now lets keep it this way
pfile=/etc/passwd_sample
# Later it should be /etc/group but for now lets keep it this way
gfile=/etc/group_sample

# ALL THIS SHOULD BE SOURCED FROM SOME CONFIGURATION FILE TOO
# -----------------------------------------------------------
# Paths to binaries #
# none yet

# AND THIS SHOULD ALSO BE SOURCED FROM A CONFIGURATION FILE
# ---------------------------------------------------------
# Defaults #
# Path to the homes of the users
defhome=/home
# Path where the backed up copies of user(owned by) files are kept
defbackup=/root/home


function get_input() { 
  local output
  if [ "`echo $BASH_VERSION | cut -b1`" = "1" ]; then
    echo -n "${1} " >&2 # fudge for use with bash v1
    read output
  else # this should work with any other /bin/sh
    read -ep "${1} " output
  fi
  echo $output
}

#: Read the login name for the new user :#
#
# Remember that most Mail Transfer Agents are case independant, so having
# 'uSer' and 'user' may cause confusion/things to break.  Because of this,
# useradd from shadow-4.0.3 no longer accepts usernames containing uppercase,
# and we must reject them, too.

# Set the login variable to the command line param

echo
LOGIN="$1"
needinput=yes
# Loop as long as needinput is set
while [ ! -z $needinput ]; do
  if [ -z "$LOGIN" ]; then 
    while [ -z "$LOGIN" ]; do LOGIN="$(get_input "Login name for new user []:")" ; done
  fi
  grep "^${LOGIN}:" $pfile >/dev/null 2>&1  # ensure it's not already used
  if [ $? -gt 0 ]; then
    echo "- User '$LOGIN' does not exist; please choose another"
    unset LOGIN
  elif [ ! -z "$( echo $LOGIN | grep "^[0-9]" )" ]; then
    echo "- User names cannot begin with a number; please choose another"
    unset LOGIN
  elif [ ! "$LOGIN" = "`echo $LOGIN | tr A-Z a-z`" ]; then # useradd does not allow uppercase
    echo "- User '$LOGIN' contains illegal characters (uppercase); please choose another"
    unset LOGIN
  elif [ ! -z "$( echo $LOGIN | grep '\.' )" ]; then
    echo "- User '$LOGIN' contains illegal characters (period/dot); please choose another"
    unset LOGIN
  else
    # Okhey we've our user name, lets break out of this loop
    unset needinput
  fi
done


function del_user_from_group_file() {
   for group in $(echo $* | sed 's/[^[:space:]]*[[:space:]]//'); do
      gfile_line=$(cat $gfile | sed -n /^$group/p)
      rvalue=${gfile_line##*:};
      lvalue=${gfile_line%:*};
      rvalue=$(echo $rvalue | sed 's/,/ /g' | sed s/$LOGIN//g | sed 's/[[:space:]]$//g'| sed 's/[[:space:]]/,/g');
      gfile_line=$lvalue:$rvalue;
      cat $gfile | grep -v $group >$gfile;
      echo $gfile_line >>$gfile;
   done;
   pwconv;
}


# See if group/s is/are given.
# If gorup/s is/are there(part of $*) then it is implied to only remove the 
# user from the given group/s. 
# After that exit gracefully.
if [ $# -gt 1 ]; then

   del_user_from_group_file $*;

   exit 0;   

fi;

# Delete the account. We are here because we want the complete deletion of the 
# account, by complete here means entry of $pfile file.
# All the memberships of different groups or the complete deletion of the user from
# the $gfile.
cat $pfile | sed /^$LOGIN/d >$pfile;
del_user_from_group_file $LOGIN $(groups $LOGIN); 

# Lets see if we want to backup the users home directory.
# Backed up directory will be kept at the path $defbackup.
# In order for the backup to takeplace the $defbackup directory should exists.
(
getyn="$(get_input "*  Do you wish to backup the $defhome/$LOGIN ? (Y/n) ")"
    if [ "$(echo $getyn | grep -i "y")" ]; then
       # Lets see if the directory where the backups should be kept exists.
       # If it does then do the backup 
       if [ -d $defbackup ]; then
          (cd $defhome; tar -cjf $defbackup/${LOGIN}-home.tar.bz2 $LOGIN);
       else echo "$defbackup does not exists"; echo "Unable to take the backup of $defhome/$LOGIN";   
       fi;  
    fi;
);


# Lets see if we want to keep the $defhome/$LOGIN directory.
# Keeping the home of the user who nolonger exists is not encoureged.
(
getyn="$(get_input "*  Do you wish to delete the $defhome/$LOGIN ? (Y/n) ")"
    if [ "$(echo $getyn | grep -i "y")" ]; then
       rm -rfv $defhome/$LOGIN;
    fi;
);


# Lets see if we want to backup all the files owned by the $LOGIN.
# No backup will take place if dir $defbackup does not exit.
# Now again the archive will be stored at the path $defbackup/$LOGIN.
# The file will be called ${LOGIN}-files.tar.bz2
(
getyn="$(get_input "*  Do you wish to take the backup of the files owned by the $LOGIN ? (Y/n) ")";
    if [ "$(echo $getyn | grep -i "y")" ]; then
       if [ -d $defbackup ]; then
          for file in $(find / -user $LOGIN); do
             if ! [ $(echo $file | grep "$defhome/$LOGIN") ]; then
                if ! [ -f $defbackup/${LOGIN}-files.tar.bz2 ]; then
                   tar -cjf $defbackup/${LOGIN}-files.tar.bz2 $file;
                else tar -cjfr $defbackup/${LOGIN}-files.tar.bz2 $file; 
                fi;
             fi;  
          done;
       fi;
    fi;
);


# Lets see if we want to delete all the files owned by the $LOGIN.
# First all the files(not dirs) owned by the $LOGIN are deleted then the directories.
# None empty directories will never get deleted. They have the files which are owned
# by the other users.
(
getyn="$(get_input "*  Do you wish to delete the files/dirs owned by the $LOGIN ? (Y/n) ")";
    if [ "$(echo $getyn | grep -i "y")" ]; then
       rm $(find / -user $LOGIN) 2>/dev/null;
       rmdir $(find / -user $LOGIN) 2>/dev/null;
    fi;
);


echo;
echo;
