#!/usr/bin/ruby
require 'thread'

@home = "/home"
@array = Array.new
@thr = Array.new
@anz_threads = 5
@mutex = Mutex.new
@command = "/usr/bin/rsync -e ssh -av -W --delete-after --delete servername:"
@timestart = Time.new
@lockfile = "/var/run/rsync_mailspool.lock"

if File.exist?(@lockfile)
	STDERR.puts "synchronization still in progress.. exiting"
	exit(1)
end
File.new(@lockfile,"w+")

Dir.foreach(@home) {
	|x|
	next if not File.stat(@home + "/" + x).directory?
	next if x =~ /^\.+|lost\+found|proj|home/
	@array << x
	}
puts


@anz_threads.times do |i|
	@thr[i] = Thread.new {
		exec = part = ""
		until @array.empty?
			@mutex.synchronize do
				part = @array.pop
			end
			exec = @command + "#{@home}/#{part} #{@home} 2>/dev/null"
			puts "executing: #{exec}"
			system(exec)
			sleep(rand(5)/1.0)
		end
	}	
end

@thr.each { |t| t.join }

@timestop = Time.new
puts "duration of syncronizetion:"
puts "%.0f minutes" % (((@timestop-@timestart).to_f) / 60 )
puts "%.0f seconds" % (((@timestop-@timestart).to_f) % 60)

File.delete(@lockfile)

