#!/usr/bin/env ruby

require 'json'
require 'open-uri'
require 'fileutils'
require 'date'

if ENV['GITHUB_TOKEN'] != ''
  all_releases = open('https://api.github.com/repos/griff/metaz/releases',
      "authorization" => "Bearer " + ENV['GITHUB_TOKEN']) do |f|
    JSON.parse(f.read, symbolize_names: true)
  end
else
  all_releases = open('https://api.github.com/repos/griff/metaz/releases') do |f|
    JSON.parse(f.read, symbolize_names: true)
  end
end  
all_releases.sort! {|a, b| b[:created_at] <=> a[:created_at] }

if !ENV['GITHUB_REF'].start_with?("refs/tags/")
  release = all_releases.select {|r| !r[:draft] }.first
  prerelease = true
else
  prerelease = false
  release = all_releases.select {|r| !r[:prerelease] && !r[:draft] }.first
  if ENV['GITHUB_REF'] == "refs/tags/#{release[:tag_name]}"
    release = all_releases.select {|r| !r[:prerelease] && !r[:draft] }[1]
  end
end
version=`/usr/libexec/PlistBuddy -c "print :CFBundleShortVersionString" "build/Release/MetaZ.app/Contents/Info.plist"`
log = `git log '--pretty=format:- %s' #{release[:tag_name]}..HEAD`
puts "### Changes in version #{version.strip} (#{Date.today.strftime('%e. %B %Y')})"
puts ''
if prerelease
  puts 'This is an automatic release generated by CI'
puts ''
end
puts 'The complete list of changes is:'
puts ''
puts log
