name: Build IPA with Fake Signing

on:
    push:
        branches: [main]
    pull_request:
        branches: [main]
    workflow_dispatch:

jobs:
    build:
        runs-on: macos-latest

        steps:
            - name: Checkout repository
              uses: actions/checkout@v4

            - name: Install ldid
              run: brew install ldid

            - name: Select Latest Xcode
              run: sudo xcode-select -switch /Applications/Xcode.app

            - name: Build Xcode Archive
              run: |
                  xcodebuild archive \
                    -project LocalDevVPN.xcodeproj \
                    -scheme LocalDevVPN \
                    -destination 'generic/platform=iOS' \
                    -archivePath build/LocalDevVPN.xcarchive \
                    CODE_SIGN_IDENTITY="" \
                    CODE_SIGNING_REQUIRED=NO \
                    CODE_SIGNING_ALLOWED=NO

            - name: Create Payload directory
              run: mkdir -p Payload

            - name: Copy App to Payload
              run: cp -R build/LocalDevVPN.xcarchive/Products/Applications/LocalDevVPN.app Payload/LocalDevVPN.app

            - name: Find and Sign App Extension
              run: |
                  APPEX_PATH=$(find Payload/LocalDevVPN.app/PlugIns -name "*.appex" | head -n 1)
                  if [ -z "$APPEX_PATH" ]; then
                    echo "Error: App Extension (.appex) not found in PlugIns directory."
                    exit 1
                  fi
                  echo "Found App Extension at: $APPEX_PATH"
                  # Use the specific entitlements for the extension
                  ldid -S"${GITHUB_WORKSPACE}/TunnelProv/TunnelProv.entitlements" "$APPEX_PATH/$(basename "$APPEX_PATH" .appex)"
                  echo "Signed App Extension."

            - name: Sign Main App Bundle
              run: |
                  APP_BINARY_PATH="Payload/LocalDevVPN.app/LocalDevVPN"
                  # Use the specific entitlements for the main app
                  ldid -S"${GITHUB_WORKSPACE}/LocalDevVPN/LocalDevVPN.entitlements" "$APP_BINARY_PATH"
                  echo "Signed Main App Bundle."

            - name: Create IPA
              run: |
                  zip -r ./LocalDevVPN-fakesigned.ipa Payload

            - name: Upload IPA Artifact
              uses: actions/upload-artifact@v4
              with:
                  name: LocalDevVPN-IPA.ipa
                  path: LocalDevVPN-fakesigned.ipa
