default_platform(:mac)

def notify_git(action)
  sh("pingme", "About to run: #{action}")
end

platform :mac do

  lane :release do

    # check_apple_agreement(
    #   apple_id: "ospfranco@protonmail.com",
    #   password: ENV["FASTLANE_PORTAL_PASSWORD"]
    # )

    Dir.chdir("..") do
      sh("bun", "bump")
    end

    version = get_version_number(xcodeproj: "./macos/sol.xcodeproj")

    path = "/Users/osp/Developer/sol/"
    appFileName = path + "Sol.app"
    zipFileName = path + "releases/" + version + ".zip"
    
    gym(
      scheme: "release",
      configuration: "Release",
      clean: true,
      workspace: "./macos/sol.xcworkspace",
      output_directory: path,
      export_method: "developer-id"
    )

    notarize(
      package: appFileName,
      username: "ospfranco@protonmail.com",
      asc_provider: "24CMR7378R"
    )

    zip(
      path: appFileName,
      output_path: zipFileName,
      symlinks: true
    )

    set_github_release(
      repository_name: "ospfranco/sol",
      api_token: ENV["GITHUB_API_TOKEN"],
      tag_name: version,
      is_generate_release_notes: true,
      upload_assets: [zipFileName]
    )

    release_notes = lane_context[SharedValues::SET_GITHUB_RELEASE_JSON]["body"]

    file_url = "https://github.com/ospfranco/sol/releases/download/" + version + "/" + version + ".zip"
    
    
    Dir.chdir("..") do
      sh("./macos/Pods/Sparkle/bin/generate_appcast", "releases")

      sh("./scripts/appcast.js", file_url, version, release_notes)

      Dir.glob("#{path}releases/*.zip").each { |file| File.delete(file) }

      notify_git("git add .")
      sh("git", "add", ".")

      sh("git", "commit", "-m", version)

      sh("git", "push")
    end

    sh("cp", "-R", appFileName, "/Applications/")

    sh("open", "/Applications/Sol.app")

    sh("pingme", "Sol " + version + " released")
  end
end
