require 'rake/clean'
require 'fileutils'

vimFolder = File.expand_path("~/.config/vim")
vimRuntimeFolder = "#{vimFolder}/runtime"
bundles_dir = File.join("#{vimRuntimeFolder}/bundle")
pluginsFile = File.join("#{vimFolder}/plugins.txt")

CLEAN.include "#{bundles_dir}"

task :default => ['clean', 'vim:reinstall']


namespace :vim do

  directory "#{bundles_dir}"
  desc "reinstalls all vim plugins from #{pluginsFile} into #{bundles_dir}"
  task :reinstall do
    puts "loading plugins into #{bundles_dir}..."
    lines = IO.readlines pluginsFile
    puts "Loading #{lines.length} plugins..."
    lines.each { |source|
      if source[0] != "#" then
        loadTask = Rake::Task['vim:downloadPlugin']
        loadTask.invoke source.sub "\n", ''
        loadTask.reenable()
      end
    }
    puts "Plugins installed!"
  end

  desc "downloads a vim plugin from a git repo, installs it into #{bundles_dir}"
  task :downloadPlugin, [:source] => "#{bundles_dir}" do |t, args|
    raise "Must specify git repo to pull from." unless args.source not(nil)
    dir = gitName args.source
    puts "Installing #{dir}...."
    Dir.chdir bundles_dir do
      sh "git clone #{args.source} #{dir}"
      FileUtils.rm_rf(File.join(dir, ".git"))
    end
    puts "\n\n"
  end


  desc "downloads a new plugin into #{bundles_dir} and adds it to #{pluginsFile}"
  task :install, [:sourceName] do |t, args|
    raise "Must specify git repo to pull from." unless args.sourceName not(nil)
    source = "git://github.com/#{args.sourceName}.git"
    Rake::Task['vim:downloadPlugin'].invoke source
    puts "Adding to #{pluginsFile}"
    File.open pluginsFile, 'a' do |file|
      file.puts "#{source}\n"
    end
  end

end

def gitName(gitRepo)
    return gitRepo.split('/').last.sub(/\.git$/, '')
end

