# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

default_platform(:ios)

desc 'Build, Archive, and Upload to ASC'
lane :release do
  app_identifier = ENV['APP_IDENTIFIER']
  scheme = ENV['SCHEME']
  configuration = 'App Store Release'

  # Signal provisioning
  sigh(
    app_identifier: app_identifier,
    template_name: 'Unrestricted PushKit entitlement for iOS 13 U68MSDN6DR (Dist)'
  )
  update_project_provisioning(
    target_filter: "^Signal$",
    build_configuration: configuration,
    profile: "./AppStore_#{app_identifier}.mobileprovision"
  )

  # NSE provisioning
  sigh(
    app_identifier: "#{app_identifier}.NotificationServiceExtension",
    template_name: 'Notification Service Extension Filtering iOS (Dist)'
  )
  update_project_provisioning(
    target_filter: "^NotificationServiceExtension$",
    build_configuration: configuration,
    profile: "./AppStore_#{app_identifier}.NotificationServiceExtension.mobileprovision"
  )

  # SAE Provisioning
  sigh(
    app_identifier: "#{app_identifier}.shareextension",
    template_name: 'Unrestricted PushKit entitlement for iOS 13 U68MSDN6DR (Dist)'
  )
  update_project_provisioning(
    target_filter: "^SignalShareExtension$",
    build_configuration: configuration,
    profile: "./AppStore_#{app_identifier}.shareextension.mobileprovision"
  )

  gym(
    workspace: 'Signal.xcworkspace',
    scheme: scheme,
    configuration: configuration,
    clean: true,
    derived_data_path: './build',
    xcargs: "WARNING_CFLAGS='$(inherited) -Wno-everything'"
  )

  # Transporter only allows uploading one instance of
  # an app at a time. To workaround and allow parallel
  # building we need to wait for the transporter lock
  # to be released.
  puts "\e[33mWaiting for transporter lock, this could take a while...\e[0m"
  lock = File.open("#{Dir.home}/.fastlane.transporter.lock", File::CREAT)
  lock.flock(File::LOCK_EX)
  puts "\e[32mTransporter lock acquired!\e[0m"

  upload_to_testflight(
    app_identifier: app_identifier,
    skip_submission: true,
    skip_waiting_for_build_processing: true,
    ipa: './Signal.ipa'
  )

  lock.flock(File::LOCK_UN)
  lock.close
end
