#!/bin/env ruby
###########
# railsenv
# simple script to check a user's rails environment for known issues
# https://gatorwiki.hostgator.com/Admin/Railsenv 
# http://git.hgfix.net/railsenv/railsenv
# Please submit all bug reports at bugs.hostgator.com
#
# (C) 2011 - HostGator.com, LLC
###########


require 'etc'
require 'optparse'
require 'fileutils'
require 'rubygems'

MYVERSION = 0.2


# stop if we can't determine if ruby is 1.8 or 1.9
if (RUBY_VERSION =~ /1\.8/)
  RUBY_LIB_PATH = '1.8'
elsif (RUBY_VERSION =~ /1\.9/)
  RUBY_LIB_PATH = '1.9'
else
  puts 'Unable to determine Ruby version. Exiting.'
  exit
end
  

puts "Rails Checker #{MYVERSION} by Robert West"

options = {}
gemenv = {}
bashenv = {}

# Option parsing
# Essentially, this just checks for a --user arg
# You don't need the --user arg if you're in the user's
# homedir. If you're not in a homedir or pass the --user
# the script will fail.

optparse = OptionParser.new do |opts|
	opts.banner = "Usage: railsenv [--user username]"
	opts.on('-h', '--help', 'Display this screen') do
		puts opts
		exit
	end
	opts.on('-u', '--user USER', 'user\'s environment to check') do |u|
		options[:user] = u || false
	end
end

begin
	optparse.parse!
rescue OptionParser::MissingArgument
	$stderr.puts "Error: #{$!}"
	exit
end

# If options[:user] is false (we didn't pass a --user arg) this will 
# check to see if we're in a homedir and use that user instead.


unless (options[:user])
  if ( Dir.getwd =~ /\/home\/([A-z0-9\-_]+)\/?/) 
	  unless (options[:user])
	  	puts "Checking User: #{$1}"
	  	options[:user] = $1
  	end
  else
	  puts "Error: --user is required unless script is run from user's homedir"
	  exit
  end
end


# simple check to make sure the user exists on the box
# also fetch homedir
begin
	homedir = Etc::getpwnam(options[:user]).dir
rescue ArgumentError
	$stderr.puts "Error: #{$!}"
	exit
end

if ( File.exists?("#{homedir}/.gemrc") )
	puts "Found #{options[:user]}'s .gemrc"
	gemrc = Gem::ConfigFile.new(["--config-file=#{homedir}/.gemrc"])
  gemrc.load_file("#{homedir}/.gemrc")
  # if their gemhome is already set to either .gem or ruby, we'll keep it
  if ( gemrc[:gemhome] == "/home/#{options[:user]}/.gem/ruby/#{RUBY_LIB_PATH}" ) 
    gemenv[:gemhome] = gemrc[:gemhome]
    unless ( File.exists?("#{homedir}/.gem/ruby/#{RUBY_LIB_PATH}") )
      FileUtils.mkpath("#{homedir}/.gem/ruby/#{RUBY_LIB_PATH}")
      FileUtils.chown(options[:user], options[:user], "#{homedir}/.gem")
    end
  elsif (gemrc[:gemhome] == "/home/#{options[:user]}/ruby/gems/#{RUBY_LIB_PATH}")
    gemenv[:gemhome] = gemrc[:gemhome]
    unless ( File.exists?("#{homedir}/ruby/gems/#{RUBY_LIB_PATH}") )
      FileUtils.mkpath("#{homedir}/ruby/gems/#{RUBY_LIB_PATH}")
      FileUtils.chown(options[:user], options[:user], "#{homedir}/ruby")
    end
  else
    gemenv[:gemhome] = "/home/#{options[:user]}/ruby/gems/#{RUBY_LIB_PATH}"
  end
  gemenv[:gempath] = ["#{gemenv[:gemhome]}", "/usr/lib/ruby/gems/#{RUBY_LIB_PATH}"]
else
  puts "#{options[:user]} has no .gemrc. We'll create one for him."
  
  # this looks awkward, but it is to ensure that gemenv[:gempath] is an array
  # and contains at least the system gem path
  gemenv[:gempath] = ["/usr/lib/ruby/gems/#{RUBY_LIB_PATH}"]
end



# Isn't this language supposed to be *less* ugly than perl?

# this will look for both ~/ruby and ~/.gem for gem directories as they 
# tend to be random which is used. We'll be setting the gemhome to ~/.gem
# but adding ~/ruby to the gempath if it exists.
if (File.exists?("#{homedir}/ruby") and File.directory?("#{homedir}/ruby"))
	puts "#{options[:user]}'s gems are in #{homedir}/ruby"
	gemenv[:gemhome] = "#{homedir}/ruby/gems/#{RUBY_LIB_PATH}"
  unless ( gemenv[:gempath].include?("#{homedir}/ruby/gems/#{RUBY_LIB_PATH}") )
    gemenv[:gempath].unshift("#{homedir}/ruby/gems/#{RUBY_LIB_PATH}")
  end
end

if (File.exists?("#{homedir}/.gem") and File.directory?("#{homedir}/.gem"))
	puts "#{options[:user]}'s gems are in #{homedir}/.gem"
	gemenv[:gemhome] = "#{homedir}/.gem/ruby/#{RUBY_LIB_PATH}"
  unless ( gemenv[:gempath].include?("#{homedir}/.gem/ruby/#{RUBY_LIB_PATH}") )
    gemenv[:gempath].unshift("#{homedir}/.gem/ruby/#{RUBY_LIB_PATH}")
  end
end

unless (File.directory?("#{homedir}/ruby") or File.directory?("#{homedir}/.gem"))
  puts "#{options[:user]} has no gems installed. We'll default to #{homedir}/.gem"
  Dir.mkdir("#{homedir}/.gem")
  FileUtils.chown(options[:user], options[:user], "#{homedir}/.gem")
  gemenv[:gemhome] = "#{homedir}/.gem/ruby/#{RUBY_LIB_PATH}"
  gemenv[:gempath] = ["#{homedir}/.gem/ruby/#{RUBY_LIB_PATH}", "/usr/lib/ruby/gems/#{RUBY_LIB_PATH}"]
end


# this creates a "correct" .gemrc for the user using information 
# gathered from their home directory and stored in gemenv
gemrc = Gem::ConfigFile.new(["--config-file=#{homedir}/.gemrc"])
gemrc[:gem] = "--remote --gen-rdoc --run-tests"
gemrc[:gemhome] = gemenv[:gemhome]
# TODO: fetch system gem path from environment. hardcoded = bad
gemrc[:gempath] = gemenv[:gempath]
gemrc.write
FileUtils.chown(options[:user], options[:user], "#{homedir}/.gemrc")

# this is probably not the most graceful way to do this.
# this currently creates a backup of the existing .bash_profile
# then creates an identical file but with the correct settings for
# GEM_HOME, GEM_PATH and RAILS_ENV.
begin
  oldbashprofile = File.readlines("#{homedir}/.bash_profile")
  File.rename("#{homedir}/.bash_profile", "#{homedir}/.bash_profile.bak")
rescue Errno::ENOENT
  puts "User's .bash_profile does not exist. We'll create one."
  File.new("#{homedir}/.bash_profile", 'w').close
  oldbashprofile = []
end
  
inbashprofile = { :gemhome => false, :gempath => false, :railsenv => false }
  
oldbashprofile.each_index do |line|
  if (oldbashprofile[line] =~ /GEM_HOME=(.+)$/)
    inbashprofile[:gemhome] = true
    oldbashprofile[line] = "export GEM_HOME=\"#{gemenv[:gemhome]}\""
  elsif (oldbashprofile[line] =~ /GEM_PATH=(.+)$/)
    inbashprofile[:gempath] = true
    oldbashprofile[line] = "export GEM_PATH=\"#{gemenv[:gempath].join(":")}\""
  elsif (oldbashprofile[line] =~ /RAILS_ENV=(.+)$/)
    inbashprofile[:railsenv] = true
    oldbashprofile[line] = "export RAILS_ENV=\"production\""
  end
end
newbashprofile = File.open("#{homedir}/.bash_profile", 'w')
oldbashprofile.each do |line|
  newbashprofile.puts(line)
end
unless (inbashprofile[:gemhome])
  newbashprofile.puts("export GEM_HOME=\"#{gemenv[:gemhome]}\"")
end
unless (inbashprofile[:gempath]) 
  newbashprofile.puts("export GEM_PATH=\"#{gemenv[:gempath].join(":")}\"")
end
unless (inbashprofile[:railsenv])
  newbashprofile.puts("export RAILS_ENV=\"production\"")
end
newbashprofile.close
FileUtils.chown(options[:user], options[:user], "#{homedir}/.bash_profile")
FileUtils.chown(options[:user], options[:user], "#{homedir}/.bash_profile.bak")

puts "Edited #{options[:user]}'s .bash_profile to include:"
puts "export GEM_HOME=#{gemenv[:gemhome]}"
puts "export GEM_PATH=#{gemenv[:gempath]}"
puts "export RAILS_ENV=production"



