#!/usr/bin/env ruby
# frozen_string_literal: true

VERSION_FILE = File.expand_path("../../lib/json_api/version.rb", __FILE__)

bump_type = ARGV[0]

unless %w[major minor patch].include?(bump_type)
  abort "Usage: bin/release [major|minor|patch]"
end

content = File.read(VERSION_FILE)
current = content.match(/VERSION\s*=\s*["'](.+?)["']/)[1]
parts = current.split(".").map(&:to_i)

new_version = case bump_type
when "major" then [parts[0] + 1, 0, 0]
when "minor" then [parts[0], parts[1] + 1, 0]
when "patch" then [parts[0], parts[1], parts[2] + 1]
end.join(".")

File.write(VERSION_FILE, content.gsub(/VERSION\s*=\s*["'].+?["']/, %(VERSION = "#{new_version}")))

puts "Bumped #{current} → #{new_version}"

system("git add #{VERSION_FILE}")
system(%(git commit -m "Bump version to #{new_version}"))

print "OTP code: "
ENV["GEM_HOST_OTP_CODE"] = $stdin.gets.strip

exec("rake release")
