on:
  workflow_call:
    inputs:
      build_type:
        description: 'Release type (release, beta)'
        required: true
        type: string
      build_name:
        description: 'Build name'
        required: true
        type: string
    secrets:
      IOS_ASC_KEY_ID:
        required: true
      IOS_ASC_ISSUER_ID:
        required: true
      IOS_ASC_KEY:
        required: true
      IOS_MATCH_REPO_SSH_KEY_BASE64:
        required: true
      IOS_MATCH_PASSWORD:
        required: true
      IOS_GOOGLE_MAPS_API_KEY:
        required: true

name: Build and release ipa to specified track

defaults:
  run:
    working-directory: frontend/ios

jobs:
  build:
    runs-on: macos-14
    env:
      # $BUNDLE_GEMFILE must be set at the job level, so it is set for all steps
      BUNDLE_GEMFILE: ${{ gitea.workspace }}/frontend/ios/Gemfile

    steps:
      - uses: https://gitea.com/actions/checkout@v4

      - name: Install Flutter
        uses: https://github.com/subosito/flutter-action@v2
        with:
          channel: stable
          flutter-version-file: ${{ gitea.workspace }}/frontend/pubspec.yaml
          architecture: x64
          cache: true

      - name: Set up ruby env
        uses: https://github.com/ruby/setup-ruby@v1
        with:
          ruby-version: 3.3
          bundler-cache: true # runs 'bundle install' and caches installed gems automatically

      - uses: GuillaumeFalourd/setup-rsync@v1.2
        # rsync is required by the google maps ios tools

      - name: Install dependencies and clean up
        run: |
          flutter pub get
          flutter precache --ios
          bundle exec pod install --allow-root
          flutter clean
          bundle exec pod cache clean --all --allow-root

      - name: Setup SSH key for match git repo
        # and mark the host as known
        run: |
          echo $MATCH_REPO_SSH_KEY | base64 --decode > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa
          ssh-keyscan -p 2222 git.kluster.moll.re > ~/.ssh/known_hosts
        env:
          MATCH_REPO_SSH_KEY: ${{ secrets.IOS_MATCH_REPO_SSH_KEY_BASE64 }}

      - name: Replace API Key from secret
        # on a macOS runner, sed requires a replacement suffix after the -i flag
        run: |
          sed -i '' -e "s/IOS_GOOGLE_MAPS_API_KEY/${{ secrets.IOS_GOOGLE_MAPS_API_KEY }}/g" Runner/AppDelegate.swift

      - name: Run fastlane lane
        run: bundle exec fastlane deploy_${{ inputs.build_type }}
        env:
          BUILD_NUMBER: ${{ gitea.run_number }}
          BUILD_NAME: ${{ inputs.build_name }}
          IOS_ASC_KEY_ID: ${{ secrets.IOS_ASC_KEY_ID }}
          IOS_ASC_ISSUER_ID: ${{ secrets.IOS_ASC_ISSUER_ID }}
          IOS_ASC_KEY: ${{ secrets.IOS_ASC_KEY }}
          MATCH_PASSWORD: ${{ secrets.IOS_MATCH_PASSWORD }}
          IOS_GOOGLE_MAPS_API_KEY: ${{ secrets.IOS_GOOGLE_MAPS_API_KEY }}
