name: Arduino IDE

on:
  push:
    branches:
      - main
    paths-ignore:
      - '.github/**'
      - '!.github/workflows/build.yml'
      - '.vscode/**'
      - 'docs/**'
      - 'scripts/**'
      - 'static/**'
      - '*.md'
    tags:
      - '[0-9]+.[0-9]+.[0-9]+*'
  workflow_dispatch:
  pull_request:
    paths-ignore:
      - '.github/**'
      - '!.github/workflows/build.yml'
      - '.vscode/**'
      - 'docs/**'
      - 'scripts/**'
      - 'static/**'
      - '*.md'
  schedule:
    - cron: '0 3 * * *' # run every day at 3AM (https://docs.github.com/en/actions/reference/events-that-trigger-workflows#scheduled-events-schedule)

env:
  # See vars.GO_VERSION field of https://github.com/arduino/arduino-cli/blob/master/DistTasks.yml
  GO_VERSION: "1.19"
  JOB_TRANSFER_ARTIFACT: build-artifacts
  CHANGELOG_ARTIFACTS: changelog

jobs:
  build:
    name: build (${{ matrix.config.os }})
    strategy:
      matrix:
        config:
          - os: windows-2019
            certificate-secret: WINDOWS_SIGNING_CERTIFICATE_PFX # Name of the secret that contains the certificate.
            certificate-password-secret: WINDOWS_SIGNING_CERTIFICATE_PASSWORD # Name of the secret that contains the certificate password.
            certificate-extension: pfx  # File extension for the certificate.
          - os: ubuntu-18.04 # https://github.com/arduino/arduino-ide/issues/259
          - os: macos-latest
            # APPLE_SIGNING_CERTIFICATE_P12 secret was produced by following the procedure from:
            # https://www.kencochrane.com/2020/08/01/build-and-sign-golang-binaries-for-macos-with-github-actions/#exporting-the-developer-certificate
            certificate-secret: APPLE_SIGNING_CERTIFICATE_P12
            certificate-password-secret: KEYCHAIN_PASSWORD
            certificate-extension: p12
    runs-on: ${{ matrix.config.os }}
    timeout-minutes: 90

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Install Node.js 16.x
        uses: actions/setup-node@v3
        with:
          node-version: '16.x'
          registry-url: 'https://registry.npmjs.org'

      - name: Install Python 3.x
        uses: actions/setup-python@v4
        with:
          python-version: '3.x'

      - name: Install Go
        uses: actions/setup-go@v3
        with:
          go-version: ${{ env.GO_VERSION }}

      - name: Install Taskfile
        uses: arduino/setup-task@v1
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          version: 3.x

      - name: Package
        shell: bash
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          AC_USERNAME: ${{ secrets.AC_USERNAME }}
          AC_PASSWORD: ${{ secrets.AC_PASSWORD }}
          AC_TEAM_ID: ${{ secrets.AC_TEAM_ID }}
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          IS_NIGHTLY: ${{ github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') }}
          IS_RELEASE: ${{ startsWith(github.ref, 'refs/tags/') }}
          CAN_SIGN: ${{ secrets[matrix.config.certificate-secret] != '' }}
        run: |
          # See: https://www.electron.build/code-signing
          if [ $CAN_SIGN = false ]; then
            echo "Skipping the app signing: certificate not provided."
          else
            export CSC_LINK="${{ runner.temp }}/signing_certificate.${{ matrix.config.certificate-extension }}"
            echo "${{ secrets[matrix.config.certificate-secret] }}" | base64 --decode > "$CSC_LINK"
            export CSC_KEY_PASSWORD="${{ secrets[matrix.config.certificate-password-secret] }}"
          fi

          if [ "${{ runner.OS }}" = "Windows" ]; then
            npm config set msvs_version 2017 --global
          fi
          npx node-gyp install
          yarn --cwd ./electron/packager/
          yarn --cwd ./electron/packager/ package

      - name: Upload [GitHub Actions]
        uses: actions/upload-artifact@v3
        with:
          name: ${{ env.JOB_TRANSFER_ARTIFACT }}
          path: electron/build/dist/build-artifacts/

  artifacts:
    name: ${{ matrix.artifact.name }} artifact
    needs: build
    if: always() && needs.build.result != 'skipped'
    runs-on: ubuntu-latest

    strategy:
      matrix:
        artifact:
          - path: '*Linux_64bit.zip'
            name: Linux_X86-64_zip
          - path: '*Linux_64bit.AppImage'
            name: Linux_X86-64_app_image
          - path: '*macOS_64bit.dmg'
            name: macOS_dmg
          - path: '*macOS_64bit.zip'
            name: macOS_zip
          - path: '*Windows_64bit.exe'
            name: Windows_X86-64_interactive_installer
          - path: '*Windows_64bit.msi'
            name: Windows_X86-64_MSI
          - path: '*Windows_64bit.zip'
            name: Windows_X86-64_zip

    steps:
      - name: Download job transfer artifact
        uses: actions/download-artifact@v3
        with:
          name: ${{ env.JOB_TRANSFER_ARTIFACT }}
          path: ${{ env.JOB_TRANSFER_ARTIFACT }}

      - name: Upload tester build artifact
        uses: actions/upload-artifact@v3
        with:
          name: ${{ matrix.artifact.name }}
          path: ${{ env.JOB_TRANSFER_ARTIFACT }}/${{ matrix.artifact.path }}

  changelog:
    needs: build
    runs-on: ubuntu-latest
    outputs:
      BODY: ${{ steps.changelog.outputs.BODY }}
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 0 # To fetch all history for all branches and tags.

      - name: Generate Changelog
        id: changelog
        env:
          IS_RELEASE: ${{ startsWith(github.ref, 'refs/tags/') }}
        run: |
          export LATEST_TAG=$(git describe --abbrev=0)
          export GIT_LOG=$(git log --pretty=" - %s [%h]" $LATEST_TAG..HEAD | sed 's/ *$//g')
          if [ "$IS_RELEASE" = true ]; then
            export BODY=$(echo -e "$GIT_LOG")
          else
            export LATEST_TAG_WITH_LINK=$(echo "[$LATEST_TAG](https://github.com/arduino/arduino-ide/releases/tag/$LATEST_TAG)")
            if [ -z "$GIT_LOG" ]; then
                export BODY="There were no changes since version $LATEST_TAG_WITH_LINK."
            else
                export BODY=$(echo -e "Changes since version $LATEST_TAG_WITH_LINK:\n$GIT_LOG")
            fi
          fi
          echo -e "$BODY"

          # Set workflow step output
          # See: https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#multiline-strings
          DELIMITER="$RANDOM"
          echo "BODY<<$DELIMITER" >> $GITHUB_OUTPUT
          echo "$BODY" >> $GITHUB_OUTPUT
          echo "$DELIMITER" >> $GITHUB_OUTPUT

          echo "$BODY" > CHANGELOG.txt

      - name: Upload Changelog [GitHub Actions]
        if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')
        uses: actions/upload-artifact@v3
        with:
          name: ${{ env.JOB_TRANSFER_ARTIFACT }}
          path: CHANGELOG.txt

  publish:
    needs: changelog
    if: github.repository == 'arduino/arduino-ide' && (github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main'))
    runs-on: ubuntu-latest
    steps:
      - name: Download [GitHub Actions]
        uses: actions/download-artifact@v3
        with:
          name: ${{ env.JOB_TRANSFER_ARTIFACT }}
          path: ${{ env.JOB_TRANSFER_ARTIFACT }}

      - name: Publish Nightly [S3]
        uses: docker://plugins/s3
        env:
          PLUGIN_SOURCE: '${{ env.JOB_TRANSFER_ARTIFACT }}/*'
          PLUGIN_STRIP_PREFIX: '${{ env.JOB_TRANSFER_ARTIFACT }}/'
          PLUGIN_TARGET: '/arduino-ide/nightly'
          PLUGIN_BUCKET: ${{ secrets.DOWNLOADS_BUCKET }}
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

  release:
    needs: changelog
    if: startsWith(github.ref, 'refs/tags/')
    runs-on: ubuntu-latest
    steps:
      - name: Download [GitHub Actions]
        uses: actions/download-artifact@v3
        with:
          name: ${{ env.JOB_TRANSFER_ARTIFACT }}
          path: ${{ env.JOB_TRANSFER_ARTIFACT }}

      - name: Get Tag
        id: tag_name
        run: |
          echo "TAG_NAME=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT

      - name: Publish Release [GitHub]
        uses: svenstaro/upload-release-action@2.4.1
        with:
          repo_token: ${{ secrets.GITHUB_TOKEN }}
          release_name: ${{ steps.tag_name.outputs.TAG_NAME }}
          file: ${{ env.JOB_TRANSFER_ARTIFACT }}/*
          tag: ${{ github.ref }}
          file_glob: true
          body: ${{ needs.changelog.outputs.BODY }}

      - name: Publish Release [S3]
        if: github.repository == 'arduino/arduino-ide'
        uses: docker://plugins/s3
        env:
          PLUGIN_SOURCE: '${{ env.JOB_TRANSFER_ARTIFACT }}/*'
          PLUGIN_STRIP_PREFIX: '${{ env.JOB_TRANSFER_ARTIFACT }}/'
          PLUGIN_TARGET: '/arduino-ide'
          PLUGIN_BUCKET: ${{ secrets.DOWNLOADS_BUCKET }}
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

  clean:
    # This job must run after all jobs that use the transfer artifact.
    needs:
      - build
      - publish
      - release
      - artifacts
    if: always() && needs.build.result != 'skipped'
    runs-on: ubuntu-latest

    steps:
      - name: Remove unneeded job transfer artifact
        uses: geekyeggo/delete-artifact@v2
        with:
          name: ${{ env.JOB_TRANSFER_ARTIFACT }}
