# frozen_string_literal: true

require 'bundler/gem_tasks'
require 'shellwords'

APP_NAME   = 'terminal-notifier.app'
VENDOR_DIR = 'vendor/terminal-notifier'
BINARY     = "#{VENDOR_DIR}/#{APP_NAME}/Contents/MacOS/terminal-notifier".freeze

desc 'Remove the vendored binary'
task :clean do
  # Scoped to the vendored app only: `vendor/` is also where `bundle install`
  # puts gems when a path is configured.
  rm_rf VENDOR_DIR
  rm_f Dir.glob('*.gem')
end

desc 'Build the application bundle and vendor it into the gem'
task :update_build do
  rm_rf VENDOR_DIR
  mkdir_p VENDOR_DIR

  # `make app` rather than xcodebuild: the Makefile builds with the Command Line
  # Tools alone, so packaging the gem does not require a full Xcode install.
  sh 'cd .. && make app'

  cp_r "../build/#{APP_NAME}", VENDOR_DIR
  chmod 0o755, BINARY

  # The published gem serves every Mac from a single upload, so a thin binary
  # here would silently ship an Intel-only or arm-only tool.
  archs = `lipo -info #{BINARY.shellescape}`
  %w[x86_64 arm64].each do |arch|
    raise "vendored binary is missing the #{arch} slice: #{archs}" unless archs.include?(arch)
  end
  puts "vendored #{archs.strip}"
end

# bundler/gem_tasks defines `build` and `release`, and `release` calls `build`.
# Neither knows about the vendored application bundle, so without this the
# published gem would contain the Ruby files and no binary at all.
task build: :update_build

desc 'Build gem'
task gem: :build

desc 'Run specs'
task :spec do
  sh 'bundle exec rspec'
end

task default: :spec
