name: pkgx/pantry/setup-codesign
description: Codesigns macOS binaries using Apple tools

inputs:
  p12-file-base64:
    description: Base64 encoded p12 file
    required: true
  p12-password:
    description: Password for p12 file
    required: true
  APPLE_IDENTITY:
    required: false

runs:
  using: composite
  steps:
    # - name: purge tool PATH
    #   run: |
    #     if [ -d /usr/local/bin ]; then
    #       tmp=$(mktemp -d)
    #       sudo mv /usr/local/bin $tmp
    #     fi
    #   shell: bash

    - name: export APPLE_IDENTITY
      run: echo 'APPLE_IDENTITY=${{inputs.identity || '-'}}' >> $GITHUB_ENV
      shell: bash

    # the next three steps bless our code for Apple. It might be the case they should be
    # encapulated separately.
    # FIXME: using an explicit commit in a PR isn't great, but the last release was almost 3 years
    # ago, and we need bugfixes.
    # FIXME: replace this with a pkgx script based on https://localazy.com/blog/how-to-automatically-sign-macos-apps-using-github-actions
    # github has a doc with similar content, but it's not returning to me atm.

    # apple-actions/import-codesign-certs will fail if the keychain already exists, so we prophylactically
    # delete it if it does.
    - name: Delete keychain
      shell: sh
      if: runner.os == 'macOS' && inputs.p12-file-password && inputs.p12-file-base64
      run: security delete-keychain signing_temp.keychain || true

    - uses: apple-actions/import-codesign-certs@v2
      if: runner.os == 'macOS' && inputs.p12-file-password && inputs.p12-file-base64
      with:
        p12-file-base64: ${{ inputs.p12-file-base64 }}
        p12-password: ${{ inputs.p12-password }}

    # Needed for self-hosted runner, since it doesn't destroy itself automatically.
    - name: Delete keychain
      uses: webiny/action-post-run@3.0.0
      if: runner.os == 'macOS' && inputs.p12-file-password && inputs.p12-file-base64
      with:
        run: security delete-keychain signing_temp.keychain
