require "dotenv"
require "open3"
require "shellwords"
require "yaml"

Dotenv.load(File.expand_path("../.env", __dir__))

default_platform(:ios)

APP_IDENTIFIER = ENV.fetch("FASTLANE_APP_IDENTIFIER", "net.buzzert.sybil2")
TEAM_ID = ENV.fetch("FASTLANE_TEAM_ID", "DQQH5H6GBD")
APP_STORE_APPLE_ID = ENV.fetch("SYBIL_APP_STORE_APPLE_ID", "6759442828")
PROVIDER_PUBLIC_ID = ENV.fetch("SYBIL_PROVIDER_PUBLIC_ID", "c043d167-ad88-4036-84ea-76c223f1b1b2")
IOS_ROOT = File.expand_path("..", __dir__)
PROJECT_FILE = File.join(IOS_ROOT, "Sybil.xcodeproj")
PROJECT_SPEC = File.join(IOS_ROOT, "project.yml")
APP_SPEC = File.join(IOS_ROOT, "Apps/Sybil/project.yml")
SCHEME = "Sybil"
TARGET = "SybilApp"

def present?(value)
  !value.to_s.strip.empty?
end

def capture(command)
  stdout, stderr, status = Open3.capture3(command)
  return stdout.strip if status.success?

  UI.user_error!("Command failed: #{command}\n#{stderr.strip}")
end

def app_project_settings
  YAML.safe_load(File.read(APP_SPEC)).fetch("targets").fetch(TARGET).fetch("settings").fetch("base")
end

def local_marketing_version
  app_project_settings.fetch("MARKETING_VERSION").to_s
end

def local_build_number
  app_project_settings.fetch("CURRENT_PROJECT_VERSION").to_i
end

def normalize_version_tag(tag)
  version = tag.to_s.strip.sub(/\Av/, "")
  unless version.match?(/\A\d+\.\d+(\.\d+)?\z/)
    UI.user_error!("Release tag #{tag.inspect} must look like v1.10 or v1.10.0")
  end
  version
end

def release_version
  tag = ENV["SYBIL_VERSION_TAG"]
  tag = capture("git describe --tags --abbrev=0") unless present?(tag)
  normalize_version_tag(tag)
end

def xcode_build_setting(key, value)
  "#{key}=#{value.to_s.shellescape}"
end

def app_store_connect_key_options
  key_id = ENV["APP_STORE_CONNECT_API_KEY_ID"]
  issuer_id = ENV["APP_STORE_CONNECT_API_ISSUER_ID"]
  return nil unless present?(key_id) && present?(issuer_id)

  key_path = ENV["APP_STORE_CONNECT_API_KEY_PATH"]
  key_content = ENV["APP_STORE_CONNECT_API_KEY_CONTENT"]
  if present?(key_path)
    {
      key_id: key_id,
      issuer_id: issuer_id,
      key_filepath: key_path
    }
  elsif present?(key_content)
    {
      key_id: key_id,
      issuer_id: issuer_id,
      key_content: key_content,
      is_key_content_base64: ENV["APP_STORE_CONNECT_API_KEY_CONTENT_BASE64"].to_s == "true"
    }
  end
end

platform :ios do
  desc "Show the version Fastlane will stamp into the next TestFlight archive"
  lane :version do
    UI.message("Git tag version: #{release_version}")
    UI.message("Checked-in app version: #{local_marketing_version}")
    UI.message("Checked-in build number: #{local_build_number}")
  end

  desc "Build Sybil and upload it to TestFlight"
  lane :beta do
    version = release_version
    build_number = ENV["SYBIL_BUILD_NUMBER"].to_s
    api_key = nil

    if app_store_connect_key_options
      api_key = app_store_connect_api_key(app_store_connect_key_options)
    end

    unless present?(build_number)
      build_number = (local_build_number + 1).to_s

      if api_key
        begin
          latest = latest_testflight_build_number(
            app_identifier: APP_IDENTIFIER,
            version: version,
            api_key: api_key,
            initial_build_number: local_build_number
          ).to_i
          build_number = [latest + 1, local_build_number + 1].max.to_s
        rescue StandardError => e
          UI.important("Could not look up TestFlight build number: #{e.message}")
          UI.important("Using checked-in build number + 1: #{build_number}")
        end
      end
    end

    UI.user_error!("Build number must be a positive integer") unless build_number.match?(/\A[1-9]\d*\z/)

    sh("xcodegen --spec #{PROJECT_SPEC.shellescape}")

    xcode_args = [
      "-allowProvisioningUpdates",
      xcode_build_setting("MARKETING_VERSION", version),
      xcode_build_setting("CURRENT_PROJECT_VERSION", build_number)
    ].join(" ")

    ipa_path = build_app(
      project: PROJECT_FILE,
      scheme: SCHEME,
      clean: true,
      sdk: "iphoneos",
      export_method: "app-store",
      output_directory: File.join(IOS_ROOT, "build/fastlane"),
      output_name: "Sybil-#{version}-#{build_number}.ipa",
      xcargs: xcode_args,
      export_xcargs: "-allowProvisioningUpdates",
      export_options: {
        method: "app-store-connect",
        destination: "export",
        signingStyle: "automatic",
        teamID: TEAM_ID,
        manageAppVersionAndBuildNumber: false,
        uploadSymbols: true,
        stripSwiftSymbols: true
      }
    )

    ipa_path ||= lane_context[SharedValues::IPA_OUTPUT_PATH]
    UI.user_error!("IPA export failed; no IPA path was returned") unless present?(ipa_path) && File.exist?(ipa_path)

    password = ENV["FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD"]
    UI.user_error!("FASTLANE_USER is required for altool upload") unless present?(ENV["FASTLANE_USER"])
    UI.user_error!("FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD is required for altool upload") unless present?(password)
    UI.user_error!("SYBIL_APP_STORE_APPLE_ID is required for altool upload") unless present?(APP_STORE_APPLE_ID)
    UI.user_error!("SYBIL_PROVIDER_PUBLIC_ID is required for altool upload") unless present?(PROVIDER_PUBLIC_ID)

    ENV["ITMS_TRANSPORTER_PASSWORD"] = password
    sh([
      "xcrun altool",
      "--upload-package #{ipa_path.shellescape}",
      "--platform ios",
      "--apple-id #{APP_STORE_APPLE_ID.shellescape}",
      "--bundle-id #{APP_IDENTIFIER.shellescape}",
      "--bundle-version #{build_number.shellescape}",
      "--bundle-short-version-string #{version.shellescape}",
      "--provider-public-id #{PROVIDER_PUBLIC_ID.shellescape}",
      "--username #{ENV.fetch("FASTLANE_USER").shellescape}",
      "--password @env:ITMS_TRANSPORTER_PASSWORD",
      "--show-progress"
    ].join(" "))
  end
end
