Skip to content

Instantly share code, notes, and snippets.

@andyl
Created December 15, 2010 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyl/742336 to your computer and use it in GitHub Desktop.
Save andyl/742336 to your computer and use it in GitHub Desktop.
set_routes script
class Vhost < Thor
include Thor::Actions
no_tasks do
def initialize(*args)
@vhost_dir = File.expand_path "~/.vhost"
@app_dir = File.expand_path "~/lcl/nconf"
@adblock_file = File.expand_path "~/util/bin/templates/adblock.txt"
super args
end
def write_hosts_file
address = "127.0.0.1".ljust(20)
output = []
output << "# Generated by vhost (~/util/bin/vhost)"
output << "# #{Time.now}"
output << " "
output << "#{address}localhost #{`hostname`.chomp} lh"
output << " "
Dir["#{@vhost_dir}/*"].each {|d| output << `cat #{d}`}
output << `cat #{@adblock_file} 2>/dev/null`
File.open("/etc/hosts", "w") { |f| f.puts output.join("\n") }
end
def call_ping(host)
x = `ping #{host} -c 1 2>/dev/null | grep PING`
x.empty? ? nil : x
end
def get_address_from_ping(ping)
/\(([0-9.]+)\)/.match(ping).captures.first
end
def address(host)
return nil unless x = call_ping(host)
get_address_from_ping(x)
end
def gen_list_of_app_directories(host)
result = `ssh #{host} vhost_dirlist #{@app_dir} 2> /dev/null`
result.chomp.split("\n")
end
def write_vhost_file(host, app_directories, ip)
File.open("#{@vhost_dir}/#{host}",'w') do |f|
app_directories.each do |dir|
f.puts "#{ip.ljust(20)} #{dir}.#{host}"
end
end
end
end
desc "add HOST", "add vhosts to /etc/hosts"
def add(host)
abort "Host not reachable." unless ip = address(host)
system "mkdir -p #{@vhost_dir}"
app_directories = gen_list_of_app_directories(host)
write_vhost_file(host, app_directories, ip)
write_hosts_file
list
end
desc "del HOST", "delete vhosts from /etc/hosts"
def del(host)
system "rm -f #{@vhost_dir}/#{host}"
write_hosts_file
list
end
desc "clear", "clear all vhost entries from /etc/hosts"
def clear
system "rm -f #{@vhost_dir}/*" if File.exist?(@vhost_dir)
write_hosts_file
list
end
desc "list", "list all vhost entries in /etc/hosts"
def list
width = 40
puts " static vhosts for #{`hostname`.chomp} ".center(width, '=')
Dir["#{@vhost_dir}/*"].each do |f|
puts " #{File.basename(f)} ".center(width, '-')
puts `cat #{f}`
end
puts " "
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment