#!/usr/bin/ruby
#
# This scripts is used to create a new unix user from Samba
#

require __FILE__.sub(/[^\/]+\.rb$/, 'utils.rb')
require __FILE__.sub(/[^\/]+\.rb$/, 'config.rb')

username = ARGV[0]

log = Logger.new('/var/log/samba/adduser.log', username)
log.log('useradd called for ' + username)

`/usr/sbin/useradd -m -g users -s /bin/false #{username}`
if $?.exitstatus > 0
  log.log('Error while running useradd')
  exit $?.exitstatus
end

# Now create the profile
prof = File.join($profiles_share, username)
if !File.exists?(prof)
  begin
    `mkdir #{prof}`
    raise "Failed creating the profile folder" if $?.exitstatus > 0
    `chown #{username}:users #{prof}`
    raise "Failed changing the ownership of the profile folder" if $?.exitstatus > 0
    `chmod 700 #{prof}`
    raise "Failed changing the permissions of the profile folder" if $?.exitstatus > 0
  rescue Exception => e
    log.log('Failed creating the profile : ' + e.to_s)
    log.log('Calling the deluser script')
    `#{__FILE__.sub(/[^\/]+\.rb$/, 'deluser.rb')} #{username}`
    `mv #{prof} #{File.join($trash_folder, username+'profile')}`
    `mv #{File.join($home_folders, username)} #{$trash_folder}`
    `/usr/sbin/userdel #{username}`
    exit 1
  end
end

exit 0



