#!/bin/bash

#####################################################################
# useradd - Script for create users when command useradd is missing #
# Author: Quique Molina                                             # 
# Contact: emolina@prosodie.com                                     #
# License: GPL 2.0                                                  #
# ###################################################################
VERSION=1.0

# Function to check root permissions
function checkAdministrator() {
  mkdir -p /etc/root &> /dev/null
  administrator=$?
  if [ ${administrator} -eq 0 ] ; then
    rm -rf /etc/root
  else
    echo ""
    echo "* Administrator permissions are required."
    echo ""
    exit
  fi
}

if [ -z ${1} ] ; then
  echo ""
  echo "Usage: $0 <user> <number-id>"
  echo ""
else
  if [ -z ${2} ] ; then
    echo ""
    echo "Usage: $0 <user> <number-id>"
    echo ""
  else
    checkAdministrator
    mkdir -p /home/${1}
    num_id="${2}"
    id_usuario=$(cat /etc/passwd | grep ":${num_id}:")
    if [ -z "${id_usuario}" ] ; then
      echo "# Creating backup of passwd,group and shadow files"
      cp -rf /etc/passwd /etc/passwd.bck.${RANDOM}
      cp -rf /etc/group /etc/group.bck.${RANDOM}
      cp -rf /etc/shadow /etc/shadow.bck.${RANDOM}
      echo "# Creating entry for user ${1} on /etc/passwd"
      echo "${1}:x:${num_id}:${num_id}:${1}:/home/${1}:/bin/bash" >> /etc/passwd
      echo "# Creating entry for user ${1} on /etc/shadow"
      sleep 1
      echo "${1}:\$1\$NkqGHXtS\$ijqX7Kln11iRvSm7YUulP1:${num_id}:0:90:6:15::" >> /etc/shadow
      echo "# Creating entry for group ${1} on /etc/group"
      echo "${1}:x:${num_id}:" >> /etc/group
      echo "# Copying files from skel to /home/${1}"
      cp -rf /etc/skel/* /home/${1}
      cp -rf /etc/skel/.bash* /home/${1}
      sleep 1
      echo "# Changing permissions for home directory"
      chmod 700 -R /home/${1}
      chown ${1} -R /home/${1}
      chown ${1}.${1} -R /home/${1}
      echo "# Creating password for user ${1}"
      passwd ${1}
    else
      echo ""
      echo "* The ID number ${num_id} already exists"
      echo "+ Choose other number ID"
      echo ""
    fi
  fi
fi 
