#!/usr/bin/env ruby
require 'readline'


def ask(prompt="", newline=false)
  prompt += "\n" if newline
  Readline.readline(prompt, true).squeeze(" ").strip
end



INSTALL_LOC = Dir.home + '/betty/'

if Dir.exist? INSTALL_LOC
  puts "Warning: ~/betty already exists!"
end

puts "We will install to ~/betty and put an alias in your .<shell>rc. Hit <enter> or 'y' if this is okay."
STDOUT.flush
CONTINUE = ask "> "
if CONTINUE == "" || CONTINUE == "y"
    # copy to ~/betty/
    if Dir.exist? INSTALL_LOC
      # raise "~/betty already exists! Please manually remove if you want to proceed" 
    else
      COPY_COMMAND = 'cp -rf ' + Dir.pwd + ' ' + INSTALL_LOC
      print "Running `" + COPY_COMMAND + "`\n"
      system COPY_COMMAND 
    end

    begin
      *junk, SHELL = `echo $SHELL`.split('/') 
    rescue Exception
       SHELL="bash" #ruby 1.8 (parsing exceptions are not rescued by default)
     end
    bash_config = '.' + SHELL.chomp + 'rc'
    bash_config = '.bash_profile' if RUBY_PLATFORM.match /darwin/ #and ... ?
    
    SHELLRC = (Dir.home + '/' + bash_config ).chomp
    print "Writing an alias called `betty` to " + SHELLRC + "\n"
    open(SHELLRC, 'a') do |f|
      f.puts "\n"
      f.puts "######## Generated by Betty's install script"
      f.puts "alias betty=#{ Dir.home }/betty/main.rb"
    end
    
    puts "add auto-complete by typing"
    puts "complete -C #{INSTALL_LOC}autocomplete.rb betty"
    `#{INSTALL_LOC}autocomplete.rb`
end

