#!/bin/bash
#######################################################
#
# Createusers
# A bulk user adding program.
# Author: Phil Jones (phil@lfsp.org) 
#
# Usage: createusers [usersfile]
#
########################################################

##################
# Checks section #
##################

# See if at least one file has been specified on the command line.
if [ $# -eq 0 ]; then
   echo "Usage: createusers [filename]" >&2
   exit 1 
fi

# If more than one file specified, tell user only one file
# can be taken at a time.
if [ $# -gt 1 ]; then
   echo -n "Désolé, createusers n'accepte qu'un fichier " >&2
   echo    "à la fois."
   exit 1 
fi

# Convert DOS newlines (CR/LF) to Unix format
pid=$$
sed s/^M$// $1 > /tmp/usersfile.$pid
mv /tmp/usersfile.$pid $1

# Check the format of the input file.
echo "Vérification du fichier '$1'...";
if ! /usr/local/lib/createusers/verify_createusers_input.pl $1
then
   exit 1
fi


# Make sure the checks file is installed and executable.
if ! test -x /usr/local/lib/createusers/checks > /dev/null; then
     echo "incapable d'exécuter" \  
          "'/usr/local/lib/createusers/checks'." >&2
     exit 1
fi

# Run checks.
if ! /usr/local/lib/createusers/checks $1; then
     echo "Un ou plusieurs problèmes." >&2
     exit 1
fi


#################
# Get variables #
#################

# Get number of lines.
linecount=`/usr/local/lib/createusers/linecount.pl $1`
currentline=1

config_file="/etc/createusers.conf"

create_home_dir=`grep "^create_home_dir" \
                 $config_file`

create_common_dir=`grep "^create_common_dir" \
                 $config_file`

message_bienvenue=`grep "^message_bienvenue" \
                 $config_file`

#trouver la ligne commencant par 'other_groups'
#pour lire les noms des groupes supplementaires
a=`grep "other_groups=" $config_file`
other_groups=${a#other_groups=}

create_html_dir=`grep "^create_html_dir" \
                 $config_file`

default_shell=`grep "^default_shell" \
                 $config_file | cut -f2 -d "="`

make_mysql_databases=`grep "^make_mysql_databases" \
                     $config_file` 

mysql_server=`grep "^mysql_server" \
              $config_file | cut -f2 -d "="`

mysql_allowed_hosts=`grep "^mysql_allowed_hosts" \
                     $config_file | cut -f2 -d "="`  

make_postgres_databases=`grep "^make_postgres_databases" \
                         $config_file`

postgres_server=`grep "^postgres_server" \
                       $config_file | cut -f2 -d "="`

create_samba_users=`grep "^create_samba_users" \
                    $config_file`

quota_prototype_user=`grep "^quota_prototype_user" \
                      $config_file | cut -f2 -d "="`

####################
# Create new users #
####################

cat $1 | while read a
do
 user=`echo $a | cut -f1 -d","`
 pwd=`echo $a | cut -f2 -d","`
 name=`echo $a | cut -f3 -d","`
 grp=`echo $a | cut -f4 -d","`

 echo "Travail sur la ligne" \
       $currentline \
       "de" \
       $linecount \
       "du fichier '$1'" 

 ###################
 # Create new user #
 ###################

 ##############################
 # Login and home dir section #
 ##############################


 # Create group that user is going into
 groupadd $grp

 if [ $create_home_dir ]; then

    # Create group directory 
    if ! test -e /home/$grp; then
       echo "Création du répertoire de groupe '/home/$grp'"
       mkdir /home/$grp

       if [ $create_common_dir ]; then
          # Creation d'un répertoire commun
          mkdir --mode=775 /home/$grp/$grp
          chown -v :$grp /home/$grp/$grp
          mkdir --mode=777 /home/$grp/$grp/public
          chown -v :$grp /home/$grp/$grp/public
        fi


    else
       echo "Le répertoire de groupe '/home/$grp' existe déjà"
    fi

    if /usr/sbin/useradd -m \
                         -c "$name" \
                         -g $grp \
                         -G audio,scanner,cdrom \
                         -d /home/$grp/$user \
                         -s $default_shell \
                         $user 

    then  
       chmod -v 755 /home/$grp/$user
       echo "Ajout de l'utilisateur '$user' au groupe '$grp',"
       echo "Création du répertoire utilisateur '/home/$grp/$user'"

        if [ $create_common_dir ]; then
	   # Lien vers repertoire commun
	   ln -sv  --target-directory=/home/$grp/$user /home/$grp/$grp $grp
	   mkdir --mode=777 /home/$grp/$user/public
           chown -v $user:$grp /home/$grp/$user/public
        fi

        if [ $message_bienvenue ]; then
	   # Envoi d'un message de bienvenue pour que mail 
           # genere le fichier /var/mail/$user
	   mail -s Bienvenue $user < /etc/bienvenue.txt
        fi

    fi

 else

    if /usr/sbin/useradd -c "$name" \
			 -g $grp \
                         -G audio,admin \
			 -s $default_shell \
			 $user 
    then  
       echo "Ajout de l'utilisateur '$user' au groupe '$grp'" \
	    "sans création de répertoire"
    fi

 fi

 # Set the user's password.
 if /usr/sbin/autopasswd $user $pwd > /dev/null
 then
    echo "Le mot de passe de '$user' est '$pwd'"
 else
    echo "Impossible de créer un mot de passe pour '$user'." >&2
    exit 1
 fi

 # See if we are to set up html dir.
 if [ $create_html_dir ]; then

    # Make sure public_html directory is present in user's home.
    if ! test -d /home/$grp/$user/public_html; then
       mkdir /home/$grp/$user/public_html
       chown $user.$grp /home/$grp/$user/public_html
       echo "Créé '/home/$grp/$user/public_html'" \
	    "(http://localhost/~$user/)"
     fi
    # end if public_html dir doesn't exist

    # Allow other users to cd through the user's home directory
    # so they can get to the user's public_html directory. 
    if chmod 701 /home/$grp/$user; then
       echo "Set mode of home directory '/home/$grp/$user' to 701"
    else
       echo "Failed to set mode of '/home/$grp/$user' to 701" >&2
    fi 

 fi
 # end if create_html_dir is enabled
 
 ##################
 # MySQL section  #
 ##################

 # See if we are to create user databases.
 if [ $make_mysql_databases ]
 then

   # Create user's MySQL database. 
   mysql -h $mysql_server -u root mysql \
	 -e "create database $user" 

   # Give user full access to the MySQL database from 
   # each of the allowed hosts.
   for allowed_host in $mysql_allowed_hosts;
   do
   
     # Add user to MySQL.
     if mysql -h $mysql_server -u root mysql \
	      -e "insert into user (host,user,password) \
		  values('$allowed_host', '$user', password('$pwd')); \
		  flush privileges;" 
     then
	echo "Created MySQL user '$user' with access from '$allowed_host'"
     fi

     # Grant user access to their MySQL database.
     if mysql -h $mysql_server -u root mysql \
	      -e "GRANT ALL PRIVILEGES on $user.* to \
                  \"$user\"@\"$allowed_host\" \
		  identified by '$pwd'; \
		  flush privileges;" 
     then
	echo "Granted MySQL user '$user' access to database '$user'" \
	     "from '$allowed_host' with password '$pwd'"
     fi

   done
   # end for allowed hosts

 fi
 # end if we are to create MySQL databases


 ######################
 # PostgreSQL section #
 ######################

 if [ $make_postgres_databases ]
 then
 
    # Create PostgreSQL user account.
    if cat ~/.pg.password | psql -h $postgres_server \
                                 -U postgres \
                                 --command "create user $user \
                                            with password '$pwd' \
                                            createdb nocreateuser" \
                                 -W
    then
       echo "Created PostgreSQL user '$user' with password '$pwd'"
    fi

    # Create database for user. This is done by logging into PostgreSQL
    # as the user, connecting to the 'template1' database which always
    # exists, then creating a database with the user name. The user can
    # then log into their database and create more databases if they wish.
    if printf "$pwd\n" | psql -h $postgres_server \
                              -U $user \
                              template1 \
                              --command "create database $user" \
                              -W
    then
       echo "Created PostgreSQL database '$user' owned by user '$user'"
    fi

 fi

 #################
 # Samba section #
 #################

 # See if we are to create Samba users.
 if [ $create_samba_users ]
 then
    if /usr/bin/smbpasswd -a -s $user $pwd > /dev/null
    then 
       echo "Added Samba user $user if it does not already exist"
       echo "Set Samba password of '$user' to '$pwd'" 
    else
       echo "makeuser: Failed to update or create Samba user '$user'" >&2
       exit 1
    fi
 fi


 #################
 # Quota section #
 #################

 if [ $quota_prototype_user ] 
 then
    if edquota -p $quota_prototype_user $user
    then
       echo "Copied quota properties of user"\
            "'$quota_prototype_user' to '$user'"
    else
       echo "Failed to copy quota properties of user" \
            "'$quota_prototype_user' to '$user'" >&2
       exit 1
    fi
 fi 

 ############
 # finished #
 ############

 echo "Utilisateur '$user' Ok."
 echo "-------------------------"


 # Increment the current line status variable.
 currentline=$(( $currentline + 1 ))

done
echo "Terminé."
