name: TestFlight

on:
  workflow_dispatch:
  push:
    tags:
      - "v*"

jobs:
  testflight:
    runs-on: xcode
    defaults:
      run:
        shell: bash

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: "3.1.7"
          bundler-cache: true
          working-directory: ios

      - name: Install XcodeGen
        run: |
          set -euo pipefail
          if ! command -v xcodegen >/dev/null 2>&1; then
            brew install xcodegen
          fi

      - name: Prepare Runner Keychain
        env:
          HOME: /var/lib/act_runner
        run: |
          set -euo pipefail
          mkdir -p "${HOME}/Library/Keychains"

          login_keychain="${HOME}/Library/Keychains/login.keychain"
          if [ ! -f "${login_keychain}-db" ]; then
            security create-keychain -p "" "${login_keychain}"
          fi

          security unlock-keychain -p "" "${login_keychain}" 2>/dev/null || \
            security unlock-keychain -p "sybil-ci-keychain-password" "${login_keychain}" 2>/dev/null || true
          security default-keychain -s "${login_keychain}"
          security list-keychains -d user -s "${login_keychain}-db"
          security delete-keychain "${HOME}/Library/Keychains/sybil_ci_keychain" >/dev/null 2>&1 || true
          rm -f "${HOME}/Library/Keychains/sybil_ci_keychain" "${HOME}/Library/Keychains/sybil_ci_keychain-db"

      - name: Upload to TestFlight
        working-directory: ios
        env:
          HOME: /var/lib/act_runner
          APP_STORE_CONNECT_KEY_ID: ${{ secrets.APP_STORE_CONNECT_KEY_ID }}
          APP_STORE_CONNECT_ISSUER_ID: ${{ secrets.APP_STORE_CONNECT_ISSUER_ID }}
          APP_STORE_CONNECT_KEY_CONTENT: ${{ secrets.APP_STORE_CONNECT_KEY_CONTENT }}
          MATCH_PASSWORD: ${{ secrets.MATCH_PASSWORD }}
          MATCH_GIT_URL: ${{ secrets.MATCH_GIT_URL }}
          MATCH_GIT_BASIC_AUTHORIZATION: ${{ secrets.MATCH_GIT_BASIC_AUTHORIZATION }}
          FASTLANE_SKIP_UPDATE_CHECK: "1"
          FASTLANE_XCODEBUILD_SETTINGS_TIMEOUT: "120"
        run: |
          export PATH="/Users/runner/hostedtoolcache/Ruby/3.1.7/arm64/bin:${PATH}"
          ruby --version
          bundle exec fastlane ios beta
