#! /usr/bin/ruby
# usage: rip-config
#
# Prints sh(1) code which can be used to activate rip for the shell.
#
# TODO: Right now it's actually bash code. I plan to convert it once I
#       get done reading dash(1).

RIPDIR = ENV['RIPDIR']
RIPENV = ENV['RIPENV'] || 'active'
push = ARGV.delete('--push')
pop = ARGV.delete('--pop')

def clean_env_path(name, subdir)
  if ENV[name] =~ /:?#{RIPDIR}\/(\w+)\/#{subdir}/ && $1 != RIPENV
    re = $&.sub(/#{RIPDIR}/, "$RIPDIR").gsub('/', '\/')
    "${#{name}/#{re}}"
  else
    "$#{name}"
  end
end

RUBYLIB = pop ? ENV['RUBYLIB'] : clean_env_path('RUBYLIB', 'lib')
PATH    = pop ? ENV['PATH']    : clean_env_path('PATH', 'bin')
MANPATH = pop ? ENV['MANPATH'] : clean_env_path('MANPATH', 'man')

if push || pop
  ripenv = ARGV[0]
  abort "I need a ripenv." if ripenv.to_s.empty?
  require 'rip'
  abort "Can't find ripenv `#{ripenv}'" if !Rip.envs.include?(ripenv)
  HAS_STACKED_ENV = /:#{RIPDIR}\/#{ripenv}\/lib/

  if push
    if ENV['RUBYLIB'][HAS_STACKED_ENV]
      abort "ripenv `#{ripenv}' has already been pushed"
    end

    puts <<-PUSH
export PATH="#{PATH}:$RIPDIR/#{ripenv}/bin";
export RUBYLIB="#{RUBYLIB}:$RIPDIR/#{ripenv}/lib";
export MANPATH="#{MANPATH}:$RIPDIR/#{ripenv}/man";
    PUSH
  elsif pop
    unless ENV['RUBYLIB'][HAS_STACKED_ENV]
      abort "ripenv `#{ripenv}' hasn't been pushed yet"
    end

    path = PATH.sub(/:#{RIPDIR}\/#{ripenv}\/bin/, '')
    rubylib = RUBYLIB.sub(/:#{RIPDIR}\/#{ripenv}\/lib/, '')
    manpath = MANPATH.sub(/:#{RIPDIR}\/#{ripenv}\/man/, '')
    puts <<-POP
export PATH="#{path}";
export RUBYLIB="#{rubylib}";
export MANPATH="#{manpath}";
    POP
  end
  exit
end

if ENV['RIPHELPERS'] != '0'
  puts <<-end_functions
function rip-push() {
  eval `rip-config --push $1`;
};
function rip-pop() {
  eval `rip-config --pop $1`;
};
function rip-use {
  export RIPENV=$1;
  eval `rip-config`;
};
  end_functions
end

puts "export RIPENV=#{RIPENV}" if RIPENV != 'active'

puts <<-end_shellcode
RIPVERBOSE=1
RIPDIR=${RIPDIR:-"$HOME/.rip"}
RUBYLIB="$RIPDIR/#{RIPENV}/lib:#{RUBYLIB}"
PATH="$RIPDIR/#{RIPENV}/bin:#{PATH}"
MANPATH="$RIPDIR/#{RIPENV}/man:#{MANPATH}"
export RIPVERBOSE RIPDIR RUBYLIB PATH MANPATH
end_shellcode
