---
name: package and draft GitHub release
# https://github.com/product-os/flowzone/tree/master/.github/actions
inputs:
  json:
    description: 'JSON stringified object containing all the inputs from the calling workflow'
    required: true
  secrets:
    description: 'JSON stringified object containing all the secrets from the calling workflow'
    required: true
  variables:
    description: 'JSON stringified object containing all the variables from the calling workflow'
    required: true

  # --- custom environment
  XCODE_APP_LOADER_EMAIL:
    type: string
    default: 'accounts+apple@balena.io'
  NODE_VERSION:
    type: string
    default: '20.x'
  VERBOSE:
    type: string
    default: 'true'

runs:
  # https://docs.github.com/en/actions/creating-actions/creating-a-composite-action
  using: 'composite'
  steps:
    - name: Download custom source artifact
      uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
      with:
        name: custom-${{ github.event.pull_request.head.sha || github.event.head_commit.id }}-${{ runner.os }}-${{ runner.arch }}
        path: ${{ runner.temp }}

    - name: Extract custom source artifact
      shell: pwsh
      working-directory: .
      run: tar -xf ${{ runner.temp }}/custom.tgz

    - name: Setup Node.js
      uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4
      with:
        node-version: ${{ inputs.NODE_VERSION }}
        cache: npm

    - name: Set up Python 3.11
      if: runner.os == 'macOS'
      uses: actions/setup-python@65d7f2d534ac1bc67fcd62888c5f4f3d2cb2b236 # v4
      with:
        python-version: "3.11"

    - name: Install additional tools
      if: runner.os == 'Windows'
      shell: bash
      run: |
        choco install yq

    - name: Install additional tools
      if: runner.os == 'macOS'
      shell: bash
      run: |
        brew install coreutils

    # https://www.electron.build/code-signing.html
    # https://github.com/Apple-Actions/import-codesign-certs
    - name: Import Apple code signing certificate
      if: runner.os == 'macOS'
      uses: apple-actions/import-codesign-certs@8f3fb608891dd2244cdab3d69cd68c0d37a7fe93 # v2
      with:
        p12-file-base64: ${{ fromJSON(inputs.secrets).APPLE_SIGNING }}
        p12-password: ${{ fromJSON(inputs.secrets).APPLE_SIGNING_PASSWORD }}

    - name: Import Windows code signing certificate
      if: runner.os == 'Windows'
      shell: powershell
      run: |
        Set-Content -Path ${{ runner.temp }}/certificate.base64 -Value $env:SM_CLIENT_CERT_FILE_B64
        certutil -decode ${{ runner.temp }}/certificate.base64 ${{ runner.temp }}/Certificate_pkcs12.p12
        Remove-Item -path ${{ runner.temp }} -include certificate.base64
      env:
        SM_CLIENT_CERT_FILE_B64: ${{ fromJSON(inputs.secrets).SM_CLIENT_CERT_FILE_B64 }}

    # https://github.com/product-os/scripts/tree/master/shared
    # https://github.com/product-os/balena-concourse/blob/master/pipelines/github-events/template.yml
    - name: Package release
      shell: bash
      run: |
        set -ea

        [[ '${{ inputs.VERBOSE }}' =~ on|On|Yes|yes|true|True ]] && set -x

        runner_os="$(echo "${RUNNER_OS}" | tr '[:upper:]' '[:lower:]')"
        runner_arch="$(echo "${RUNNER_ARCH}" | tr '[:upper:]' '[:lower:]')"

        if [[ $runner_os =~ darwin|macos|osx ]]; then
            CSC_KEY_PASSWORD='${{ fromJSON(inputs.secrets).APPLE_SIGNING_PASSWORD }}'
            CSC_KEYCHAIN=signing_temp
            CSC_LINK=${{ fromJSON(inputs.secrets).APPLE_SIGNING }}

        elif [[ $runner_os =~ windows|win ]]; then
            SM_HOST=${{ fromJSON(inputs.secrets).SM_HOST }}
            SM_API_KEY=${{ fromJSON(inputs.secrets).SM_API_KEY }}
            SM_CLIENT_CERT_FILE='${{ runner.temp }}\Certificate_pkcs12.p12'
            SM_CLIENT_CERT_PASSWORD=${{ fromJSON(inputs.secrets).SM_CLIENT_CERT_PASSWORD }}
            SM_CODE_SIGNING_CERT_SHA1_HASH=${{ fromJSON(inputs.secrets).SM_CODE_SIGNING_CERT_SHA1_HASH }}

            curl --silent --retry 3 --fail https://one.digicert.com/signingmanager/api-ui/v1/releases/smtools-windows-x64.msi/download \
              -H "x-api-key:$SM_API_KEY" \
              -o smtools-windows-x64.msi
            msiexec -i smtools-windows-x64.msi -qn
            PATH="/c/Program Files/DigiCert/DigiCert One Signing Manager Tools:${PATH}"
            smksp_registrar.exe list
            smctl.exe keypair ls
            /c/Windows/System32/certutil.exe -csp "DigiCert Signing Manager KSP" -key -user
            smksp_cert_sync.exe

            # (signtool.exe) https://github.com/actions/runner-images/blob/main/images/win/Windows2019-Readme.md#installed-windows-sdks
            PATH="/c/Program Files (x86)/Windows Kits/10/bin/${runner_arch}:${PATH}"
        fi

        npm run package

        find dist -type f -maxdepth 1

      env:
        # https://github.blog/2020-08-03-github-actions-improvements-for-fork-and-pull-request-workflows/#improvements-for-public-repository-forks
        # https://docs.github.com/en/actions/managing-workflow-runs/approving-workflow-runs-from-public-forks#about-workflow-runs-from-public-forks
        CSC_FOR_PULL_REQUEST: true
        # https://docs.digicert.com/es/software-trust-manager/ci-cd-integrations/plugins/github-custom-action-for-keypair-signing.html
        TIMESTAMP_SERVER: http://timestamp.digicert.com
        # Apple notarization (automation/build-bin.ts)
        XCODE_APP_LOADER_EMAIL: ${{ inputs.XCODE_APP_LOADER_EMAIL }}
        XCODE_APP_LOADER_PASSWORD: ${{ fromJSON(inputs.secrets).XCODE_APP_LOADER_PASSWORD }}
        XCODE_APP_LOADER_TEAM_ID: ${{ inputs.XCODE_APP_LOADER_TEAM_ID }}

    - name: Upload artifacts
      uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
      with:
        name: gh-release-${{ github.event.pull_request.head.sha || github.event.head_commit.id }}-${{ strategy.job-index }}
        path: dist
        retention-days: 1
        if-no-files-found: error
