#!/bin/bash

#######################################################
#
# updateuserpasswd 
# Changes the password of the specified user. Alters
# password for the user's login, MySQL database 
# and Samba account.
#
# Author: Phil Jones (phil@lfsp.org) 
#
# Usage: updateuserpasswd user_name pwd 
# Example: updateuserpasswd user1 password
#
########################################################

#################
# Main code     #
################# 

# Get variables

config_file=/etc/createusers.conf

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

mysql_server=`grep "^mysql_server" \
                     $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`


# See if the right number of parameters have been specified 
# on the command line.
if [ $# -ne 2 ] 
then
 echo "Usage: updateuserpasswd [user] [pwd]" 
 exit
fi


# Put variables from the command line into named variables.
user="$1"
pwd="$2"


# Get the home directory of the target user.
home=`grep ^$user: /etc/passwd | cut -f6 -d ":"`


# Change the system account password
if /usr/sbin/autopasswd $user $pwd > /dev/null; then
   echo "Setting login password of '$user' to '$pwd'"
else
   echo "Unable to change password of '$user'" >&2
fi


##################
# MySQL section  #
##################

if [ $make_mysql_databases ]; then
   if mysql -h $mysql_server -u root mysql \
            -e "update user set password=password('$pwd') \
             where user='$user'; \
             flush privileges;" 
   then
      echo "Set MySQL user '$user' password to '$pwd'"
   fi
fi

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

if [ $make_postgres_databases ]
then
 
   # Remove PostgreSQL user database. 
   if cat ~/.pg.password | psql -h $postgres_server \
                                -U postgres \
                                --command "alter user $user \
                                           with password '$pwd'" \
                                -W
   then
      echo "Set PostgreSQL user '$user' password to '$pwd'"
   fi
fi 


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

if [ $create_samba_users ]
then
   if smbpasswd -a -s $user $pwd > /dev/null
   then
      echo "Setting Samba password of '$user' to '$pwd'"
   else
      echo "Failed to update password of Samba user '$user'" >&2
   fi
fi  


#################
# Give feedback #
#################

echo "Done user '$user'."
