#! /usr/bin/ruby
# Usage: rip-install [-f] PATH
#
# Installs a library into $RIPDIR/$RIPENV
# If -f (force) is given, doesn't check for conflicts.
# If -p (pretend) is given, prints what would be installed.
# If -o (only) is given, doesn't install dependencies.

$-e = true
force = ARGV.delete('-f') || ARGV.delete('--force')
pretend = ARGV.delete('-p')
only = ARGV.delete('-o') || ARGV.delete('--only')

require 'rip/script'

abort "what?" if ARGV.empty?

paths = []

if only
  rip("package", *ARGV) do |path|
    paths << path
  end
else
  # Grab package and all dependencies
  rip_io("fetch-dependencies", "r+") do |f|
    rip("package", *ARGV) do |path|
      paths << path
      f.puts(path)
    end
    f.close_write

    f.each_line { |line| paths << line.chomp }
    f.close_read
  end
end

# See if we have any conflicts
rip "detect-conflicts", *paths if force.nil?

# Continue on.
env = Environment.new(paths)

# Install all else if not.
env.packages.each do |package|
  path = paths.shift
  package = metadata(path)

  if pretend
    puts "#{package.source} #{package.version(:long)}"
  else
    rip "import", path
    warn "installed #{package}"
  end
end
