#
# Rakefile for cache repository
#

require "rubygems"
require "nexus_cli"
require "net/ssh"
require "net/scp"

task :pull_cache, :vista_ip, :username, :ssh_key do |t, args|
  puts "INFO:  Pulling the cache.dat zip from #{args[:vista_ip]}"
  username = args[:username].nil? ? "ec2-user" : args[:username]
  ssh_key = args[:ssh_key].nil? ? "#{ENV['WORKSPACE']}/.chef/keys/vagrantaws_123139250088" : args[:ssh_key]
  mkdir File.expand_path("vista", File.dirname(__FILE__)) unless Dir.exist? File.expand_path("vista", File.dirname(__FILE__))
  tmp_zip_path = "/tmp/vista.zip"
	ssh = Net::SSH.start( args[:vista_ip], username, :keys => ssh_key )
  ssh.exec!('sudo ccontrol stop CACHE quietly') do |ch, stream, line|
    puts line
  end
  ssh.exec!("sudo zip -j #{tmp_zip_path} /usr/cachesys/mgr/VISTA/CACHE.DAT") do |ch, stream, line|
    puts line
  end
  ssh.scp.download! tmp_zip_path, "vista/vista.zip"
  ssh.exec!('sudo ccontrol start CACHE') do |ch, stream, line|
    puts line
  end
  ssh.close
end

task :upload_cache, :version do |t, args|
  puts "CACHE_VERSION='#{args[:version]}'"
  puts "INFO:  Uploading cache version: #{args[:version]} to "
  puts "INFO:  https://store.vistacore.us/nexus/content/repositories/releases/us/vistacore/vista/#{args[:version]}/vista-#{args[:version]}.zip"
  artifact_path = File.expand_path("vista/vista.zip", File.dirname(__FILE__))
  upload_artifact("us.vistacore", "vista", "zip", args[:version], "releases", artifact_path)
end

task :remove_cache do
  FileUtils.rm_rf(File.expand_path("vista", File.dirname(__FILE__)))
end

def upload_artifact(group_id, artifact_id, artifact_ext, version, repository, artifact_path)
	raise "Artifact does not exist at #{artifact_path}" unless File.exist?(artifact_path)
	coordinates = "#{group_id}:#{artifact_id}:#{artifact_ext}:#{version}"
	username = ENV["NEXUS_USER_NAME"]
	password = ENV["NEXUS_PASSWORD"]
	base_url = "https://store.vistacore.us/nexus"
	nexus_remote = NexusCli::RemoteFactory.create(
	  {
	    'url' => base_url,
	    'repository' => repository,
	    'username' => username,
	    'password' => password
	  }
	)
	check_artifact_does_not_exist(nexus_remote,coordinates)
	nexus_remote.push_artifact(coordinates, artifact_path)
end

def check_artifact_does_not_exist(nexus_remote, coordinates)
	begin
		nexus_remote.get_artifact_info(coordinates)
	rescue
		return
	end
	raise "\n\n\nArtifact already exists at #{coordinates}; not uploading\n\n\n\n"
end

