#!/usr/bin/env ruby

$LOAD_PATH << File.expand_path('../../lib', __FILE__)
require 'yaml'
require 'compile_extensions'
require 'digest'
require 'fileutils'
require 'open3'

original_url      = ARGV[0]
install_directory = ARGV[1]
file_location     = File.join(install_directory, original_url.split('/').last)
manifest_location = File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "manifest.yml"))
manifest          = YAML.load_file(manifest_location)
dependencies      = CompileExtensions::Dependencies.new(manifest)
translated_uri    = CompileExtensions::URITranslator.translate(original_url)
filtered_uri      = CompileExtensions::URITranslator.filter_uri(translated_uri)
dependency_sha256 = dependencies.find_sha256(original_url)

_, status = Open3.capture2e('curl', '-s', '-L', '-f', translated_uri, '-o', file_location)
if !status.success?
	puts "ERROR: Failed to download dependency #{filtered_uri}"
	exit 3
end

generated_sha256 = Digest::SHA256.file(file_location).hexdigest

puts filtered_uri

if dependency_sha256 == generated_sha256
  exit 0
else
  puts "DEPENDENCY_SHA256_MISMATCH for #{filtered_uri}: generated sha256: #{generated_sha256}, expected sha256: #{dependency_sha256}"
  FileUtils.rm(file_location)
  exit 3
end
