
def create_license(short_name, name, identifier, url, version_identifier, date, version_url)
  license = License.new(:short_name => short_name, :name => name, :identifier => identifier, :url => url)

  version = license.versions.build(:identifier => version_identifier, :date => date, :url => version_url)

  license.save
end


namespace :licenses do
  desc "creates default licenses, imports them, and removes the license custom field from ohwr"
  task :all => [:reset, :create, :link, :remove_custom_field]

  desc "destroys all licenses"
  task :reset => :environment do
    License.destroy_all
    LicenseVersion.destroy_all

    Project.all.each do |p|
      p.license = nil
      p.save
    end
  end

  desc "creates default licenses"
  task :create => :environment do
    create_license("GPL", "GNU General Public License", "gpl", "http://www.gnu.org/copyleft/gpl.html", "v2.0", Date.new(1991,6,1), "http://www.gnu.org/licenses/gpl-2.0.html")
    create_license("LGPL", "GNU Library General Public License", "lgpl", "http://www.gnu.org/licenses/lgpl.html", "v2.0", Date.new(1991,6,1), "http://www.gnu.org/licenses/lgpl-2.0.html")
    create_license("TAPR OHL", "TAPR Open Hardware License", "tapr-ohl", "http://www.tapr.org/OHL", "v1.0", Date.new(2007, 5, 25), "http://www.tapr.org/TAPR_Open_Hardware_License_v1.0.txt")
    create_license("CERN OHL", "CERN Open Hardware License", "cern-ohl", nil, "v1.1", Date.new(2011,7,8), nil)
  end

  desc "associates projects to the licenses they belong to"
  task :link => :environment do
    license_custom_field_id = CustomField.find_by_type_and_name("ProjectCustomField", "Licence").id

    ["GPL", "LGPL", "TAPR OHL", "CERN OHL"].each do |license_name|
      license = License.find_by_short_name(license_name)
      license_version = license.versions.first
      Project.with_custom_values(license_custom_field_id => license_name).each do |p|
        writable_p = Project.find(p.id)
        writable_p.license = license_version
        writable_p.save
      end
    end
  end

  desc "removes the previous custom field"
  task :remove_custom_field => :environment do
    CustomField.destroy_all(:type => "ProjectCustomField", :name => "Licence")
  end

end
