PROJECT_VARS_PREFIX = "XPV_"

def load_project_vars(configuration = ENV["CONFIGURATION"])
    Actions.execute_action("Loading project env vars") do
        jsonString = %x{ xcodebuild -workspace "#{ENV['WORKSPACE']}" -scheme \"#{ENV['SCHEME']}" -configuration "#{configuration}" -showBuildSettings -json 2>/dev/null }
        dict = JSON.parse(jsonString)[0]['buildSettings']
        dict.each do |key, val|
            ENV["#{PROJECT_VARS_PREFIX}#{key}"] = val
        end
        UI.success "Project env vars loaded for configuration: #{configuration}"
    end
end

def create_local_keychain(keychain_path)

    create_keychain(
      unlock: true,
      timeout: 0,
      add_to_search_list: true,
      lock_after_timeout: false,
      path: keychain_path,
      password: ENV["MATCH_KEYCHAIN_PASSWORD"],
      step_name: "Create local keychain for build"
    )

    return keychain_path
end

def install_appcast_private_key(keychain_path, creds_path, sign_update_path)
    jsonString = File.read(creds_path)
    dict = JSON.parse(jsonString)
    success = true
    sh(
        "security",
        "-v", "add-generic-password",
        "-a", dict["account"],
        "-D", dict["kind"],
        "-s", dict["service"],
        "-w", dict["private_key"],
        "-U", "-T", sign_update_path,
        keychain_path,
        error_callback: ->(result) { success = false },
        step_name: "Installing private key for signing appcast update into keychain"
    )
    UI.user_error! "Failed installing private key" unless success
end

def compress_bundle(bundle_path, archive_path)
    success = true
    sh(
        "ditto",
        "-c",
        "-k",
        "--rsrc",
        "--keepParent",
        bundle_path,
        archive_path,
        error_callback: ->(result) { success = false },
        step_name: "Archiving bundle"
        )
    UI.user_error! "Failed archiving bundle: #{bundle_path} " unless success
end

def staple_bundle(bundle_path)
    success = true
    sh(
        "xcrun",
        "stapler",
        "staple",
        bundle_path,
        error_callback: ->(result) { success = false },
        step_name: "Stapling bundle"
        )
    UI.user_error! "Failed to staple: #{bundle_path} " unless success
end