# Copyright 2022 Espressif Systems (Shanghai) PTE LTD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This workflow build examples, store the artifacts and deploy them to github pages.
# Generates the launchpad configuration file that can be used with the url.

name: Build Examples

on:
  workflow_run:
    workflows: ["Build Docker"]
    types: [completed]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
  contents: read
  pages: write
  id-token: write

# Allow one concurrent deployment
concurrency:
  group: "pages"
  cancel-in-progress: true

jobs:
  Build-Matter:
    # Disable the job in forks
    if: ${{ github.repository_owner == 'espressif' && (github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success') }}

    runs-on: ubuntu-latest
    container:
      image: espressif/esp-matter:latest
    strategy:
      matrix:
        targets:
          - {example: light, target: esp32, prefix: wifi_matter}
          - {example: light, target: esp32c3, prefix: wifi_matter}
          - {example: light, target: esp32c6, prefix: wifi_matter}
          - {example: light, target: esp32c6, prefix: thread_matter, sdkconfig: sdkconfig.defaults.c6_thread}
          - {example: light, target: esp32h2, prefix: thread_matter}
          - {example: light_switch, target: esp32c3, prefix: wifi_matter}
          - {example: generic_switch, target: esp32c3, prefix: wifi_matter}
          - {example: icd_app, target: esp32c6, prefix: thread_matter}
          - {example: icd_app, target: esp32h2, prefix: thread_matter}
          - {example: door_lock, target: esp32c2, prefix: wifi_matter}
          - {example: door_lock, target: esp32h2, prefix: thread_matter}

    steps:
      - run: mkdir -p images
      - name: build application
        run: |
          . $IDF_PATH/export.sh
          . $ESP_MATTER_PATH/export.sh
          cd $ESP_MATTER_PATH/examples/${{ matrix.targets.example }}

          if [ "${{ matrix.targets.sdkconfig }}" != "" ]
          then
            idf.py -D SDKCONFIG_DEFAULTS="${{ matrix.targets.sdkconfig }}" set-target ${{ matrix.targets.target }} build
          else
            idf.py set-target ${{ matrix.targets.target }} build
          fi

          cd build

          TARGET_CHIP=`cat project_description.json | python3 -c 'import sys,json; print(json.load(sys.stdin)["target"])'`
          APP_BIN=`cat project_description.json | python3 -c 'import sys,json; print(json.load(sys.stdin)["app_bin"])'`
          OUT_BIN="$GITHUB_WORKSPACE/images/$TARGET_CHIP"_${{ matrix.targets.prefix }}_"$APP_BIN"
          esptool.py --chip $TARGET_CHIP merge_bin -o $OUT_BIN `cat flash_args | tr '\n' '\ '`

          # read commit ids from pre-stored files
          idf_rev=`cat /opt/espressif/esp-idf-commit.txt`
          mtr_rev=`cat /opt/espressif/esp-matter-commit.txt`
          chip_rev=`cat /opt/espressif/connectedhomeip-commit.txt`
          echo "- esp-idf: [$idf_rev](https://github.com/espressif/esp-idf/tree/$idf_rev)" >> $GITHUB_WORKSPACE/images/.esp-idf
          echo "- esp-matter: [$mtr_rev](https://github.com/espressif/esp-matter/tree/$mtr_rev)" >> $GITHUB_WORKSPACE/images/.esp-matter
          echo "- connectedhomeip: [$chip_rev](https://github.com/project-chip/connectedhomeip/tree/$chip_rev)" >> $GITHUB_WORKSPACE/images/.chip

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          include-hidden-files: true
          name: build-images-${{ matrix.targets.target }}-${{ matrix.targets.prefix }}-${{ matrix.targets.example }}
          path: images/

  Build-Rainmaker:
    # Disable the job in forks
    if: ${{ github.repository_owner == 'espressif' && (github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success') }}

    runs-on: ubuntu-latest
    container:
      image: espressif/esp-matter:latest
    strategy:
      matrix:
        targets:
          - {example: matter_light, target: esp32c3, prefix: wifi_rainmaker}
          - {example: matter_light, target: esp32h2, prefix: thread_rainmaker}
          - {example: matter_light, target: esp32c2, prefix: wifi_rainmaker}

    steps:
      - run: mkdir -p images

      - uses: actions/checkout@v4
        with:
          repository: 'espressif/esp-rainmaker'
          submodules: 'recursive'
          path: 'esp-rainmaker'

      - name: build application
        run: |
          . $IDF_PATH/export.sh
          . $ESP_MATTER_PATH/export.sh
          cd esp-rainmaker/examples/matter/${{ matrix.targets.example }}

          SDK_CFG="sdkconfig.defaults"
          if [ "${{ matrix.targets.sdkconfig }}" != "" ]; then
            SDK_CFG="$SDK_CFG;${{ matrix.targets.sdkconfig }}"
          elif [ -f sdkconfig.defaults.${{ matrix.targets.target }} ]; then
            SDK_CFG="$SDK_CFG;sdkconfig.defaults.${{ matrix.targets.target }}"
          fi

          idf.py -D SDKCONFIG_DEFAULTS="$SDK_CFG" set-target ${{ matrix.targets.target }} build
          cd build

          TARGET_CHIP=`cat project_description.json | python3 -c 'import sys,json; print(json.load(sys.stdin)["target"])'`
          APP_BIN=`cat project_description.json | python3 -c 'import sys,json; print(json.load(sys.stdin)["app_bin"])'`
          OUT_BIN="$GITHUB_WORKSPACE/images/$TARGET_CHIP"_${{ matrix.targets.prefix }}_"$APP_BIN"
          esptool.py --chip $TARGET_CHIP merge_bin -o $OUT_BIN `cat flash_args | tr '\n' '\ '`

          # record the esp-rainmaker commit
          rmaker_rev=`git rev-parse --short HEAD`
          echo "- esp-rainmaker: [$rmaker_rev](https://github.com/espressif/esp-rainmaker/tree/$rmaker_rev)" >> $GITHUB_WORKSPACE/images/.esp-rainmaker

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          include-hidden-files: true
          name: build-images-${{ matrix.targets.target }}-${{ matrix.targets.prefix }}-${{ matrix.targets.example }}
          path: images/


  deploy:
    # Disable the job in forks
    if: ${{ github.repository_owner == 'espressif' && always() && needs.Build-Matter.result == 'success' }}

    needs:
      - Build-Matter
      - Build-Rainmaker

    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    container:
      image: espressif/esp-matter:latest

    steps:
      - name: Check build status
        run: |
          echo "Build-Matter status: ${{ needs.Build-Matter.result }}"
          echo "Build-Rainmaker status: ${{ needs.Build-Rainmaker.result }}"
          
      - name: Download builds
        uses: actions/download-artifact@v4
        with:
          pattern: build-images-*
          path: images/
          merge-multiple: true
        continue-on-error: true

      - name: generate launchpad config
        run: |
          cd images/
          $ESP_MATTER_PATH/tools/launchpad/generate_launchpad_config.sh ${{ github.repository_owner }}

          # Put together the commit ids used when building the firmwares
          echo "#### Build Config" >> build_cfg.md
          [ -f .esp-idf ] && cat .esp-idf >> build_cfg.md
          [ -f .esp-matter ] && cat .esp-matter >> build_cfg.md
          [ -f .chip ] && cat .chip >> build_cfg.md
          [ -f .esp-rainmaker ] && cat .esp-rainmaker >> build_cfg.md

          tree -H '.' -L 1 --noreport -T 'ESP Matter Launchpad Artifacts' -shi --charset utf-8 -I "index.html" -o index.html

      - name: Setup Pages
        uses: actions/configure-pages@v4

      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: images/

      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4
