#!/usr/bin/ruby -w
 
puts "Which user would you like to Automatically Login?"
users = []

TEMPFILE = "/tmp/custom.conf"
ACTUALFILE = "/etc/gdm/custom.conf"

File.open("/etc/passwd", "r") do |passwd|
        while (line = passwd.gets)
                users << line.split(/:/)[0] if (line =~ /home/)
        end
end

users.each_index { |i| puts  "#{i+1}. #{users[i]}" }

if (users.size == 0)
	puts "No valid users were found to setup AutomaticLogin for."
	puts "Try creating a user using the hda web interface then rerun this script"
	exit
else
	print "> "
end

selection = STDIN.gets

if (selection.to_i > users.size or selection.to_i < 1)
        puts "Not a valid selection"
	exit
else
        i = selection.to_i - 1
	File.open(TEMPFILE, "w") do |custom|
        	custom.puts "\n#Automatically login to GNOME\n[daemon]"
        	custom.puts "AutomaticLoginEnable=true"
        	custom.puts "AutomaticLogin=" + users[i]
        	custom.puts "TimedLoginEnable=true"
       		custom.puts "TimedLogin=" + users[i]
	        custom.puts "TimedLoginDelay=0"
	end
end

puts "\nWould you like these changes to be wrote to the file #{ACTUALFILE} (y/n)?"
puts "(WARNING: THIS WILL OVERWRITE ANY CHANGES YOU HAVE MADE TO YOUR custom.conf FILE!)"
print "> "

choice = STDIN.gets

if (choice =~ /[YyNn]/)
	if (choice =~ /[Yy]/)
		File.open(ACTUALFILE, "w") do |custom|
			custom.puts "# GDM configuration storage\n\n[xdmcp]\n\n[chooser]\n\n[security]\n\n[debug]\n\n"			
			custom.puts "\n#Automatically login to GNOME\n[daemon]"
	        	custom.puts "AutomaticLoginEnable=true"
        		custom.puts "AutomaticLogin=" + users[i]
        		custom.puts "TimedLoginEnable=true"
       			custom.puts "TimedLogin=" + users[i]
		        custom.puts "TimedLoginDelay=0" 
		end
	else
	        puts "\nSee file #{TEMPFILE} for details on what should be added to /etc/gdm/custom.conf"
		exit
	end
else
	puts "That is not a valid selection"
end