name: NukiHub Nightly
on:
  workflow_dispatch:
  schedule:
  - cron: "30 0 * * *"

permissions:
  contents: write

jobs:
  check-commits:
    name: Get new commits since last successful run
    if: github.repository == 'technyon/nuki_hub'
    runs-on: ubuntu-latest
    outputs:
      has-commits: ${{ steps.commits.outputs.NEW_COMMIT_COUNT }}
    env:
      GH_TOKEN: ${{ github.token }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          submodules: recursive
      - name: Get new commits since last successful run
        id: commits
        run: |
          COUNT=$(gh api -H 'Accept: application/vnd.github+json' -H "X-GitHub-Api-Version: 2022-11-28" https://api.github.com/repos/technyon/nuki_hub/actions/workflows/nightly.yml/runs?status=success | jq '.workflow_runs[0].created_at')
          echo "NEW_COMMIT_COUNT=$(git log --oneline --since $COUNT | wc -l)" >> $GITHUB_OUTPUT
  build:
    name: Build ${{ matrix.board }} (${{ matrix.build }})
    needs: check-commits
    if: needs.check-commits.outputs.has-commits > 0
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        board: [esp32, esp32-s3, esp32-s3-oct, esp32-c3, esp32-c6, esp32-h2, esp32-solo1]
        build: [release]
    env:
      BOARD: ${{ matrix.board }}
      VARIANT: ${{ matrix.name || matrix.board }}
      BUILD: ${{ matrix.build }}
    steps:
      - name: Fix variant name
        run: |
          # remove dash character
          export VARIANT=${VARIANT//-/}
          echo "VARIANT=${VARIANT}" | tee -a ${GITHUB_ENV}
      - uses: actions/checkout@v4
        with:
          submodules: recursive
      - uses: actions/cache@v4
        with:
          path: |
            ~/.cache/pip
            ~/.platformio/.cache
            ~/.platformio/packages
          key: ${{ runner.os }}-pio-${{ matrix.board }}
      - uses: actions/setup-python@v5
        with:
          python-version: '3.9'
      - name: Install dependencies
        run: make deps
      - name: Add version info
        env:
          Version: ${{ github.run_id }}.${{ github.run_number }}.${{ github.run_attempt }}
        run: |
          sed -i "s/unknownbuildnr/$Version/g" src/Config.h
          python3 resources/config_version.py master
      - name: Build ${{ matrix.build }} PlatformIO Project ${{ matrix.board }}
        run: |
          ORIGBOARD="${BOARD}"
          if [ "$BUILD" = "debug" ]; then
            BOARD="${BOARD}_dbg"
          fi
          echo "::group::Building with PlatformIO"
            make updater_${ORIGBOARD}
            make $BOARD
          echo "::endgroup::"
      - name: Add flash script
        env:
          DOC: resources/how-to-flash.txt
          FILES: ${{ format('{0}/{1}', env.BUILD, env.VARIANT) }}
        run: |
          BOARD=`echo $BOARD | tr '[:lower:]' '[:upper:]'`

          # look for documentation on flash and copy the command
          command=`sed -n '/^Howto flash (esptool)$/,$p' ${DOC} | sed -n '/^## '"${BOARD}"'$/,\${ n; n; p; }' | head -n1`

          if [ -z "$command" ]; then
            echo "::error::Command not found in document ${DOC} for board ${BOARD}"
            exit 1
          fi

          echo -n "Command: "
          echo "$command" | tee ${FILES}/flash.sh
          chmod a+x ${FILES}/flash.sh

      - name: Upload Artifact ${{ matrix.board }}-${{ matrix.build }}
        uses: actions/upload-artifact@v4
        with:
          name: ${{ format('{0}-{1}-assets', env.VARIANT, matrix.build) }}
          path: ${{ matrix.build }}/${{ env.VARIANT }}
  ota-nightly:
    name: Create nightly from latest master
    needs: [check-commits, build]
    if: needs.check-commits.outputs.has-commits > 0
    runs-on: ubuntu-latest
    steps:
      - name: Git Checkout
        uses: actions/checkout@v4
        with:
          ref: binary
      - name: Git Checkout master
        uses: actions/checkout@v4
        with:
          ref: master
          path: master
          sparse-checkout: |
              resources/ota_manifest.py
              src/Config.h
      - name: Git Commands
        run: |
          git checkout --orphan newBinary
          git branch -D binary
          git branch -M binary
          git rm --cached --ignore-unmatch -r *
      - name: Download release assets
        uses: actions/download-artifact@v4
        with:
          path: release
          pattern: '*-release-assets'
      - name: Copy binaries to ota/master
        env:
          Version: ${{ github.run_id }}.${{ github.run_number }}.${{ github.run_attempt }}
        run: |
          mkdir -p ota/beta/
          mkdir -p ota/master/
          mkdir -p webflash/
          mkdir -p resources/
          mkdir -p src/
          cp -vf release/*/nuki_hub_*.bin ota/master/
          cp -vf master/resources/ota_manifest.py resources/ota_manifest.py
          cp -vf master/src/Config.h src/Config.h
          python3 resources/ota_manifest.py master $Version
          find * -not -path "ota*" -not -path "webflash*" -delete
          rm -rf .github .gitignore .gitmodules
          touch ota/beta/empty
          touch ota/master/empty
          touch webflash/empty
      - name: Commit binaries to binary
        uses: stefanzweifel/git-auto-commit-action@v5
        with:
          commit_message: "Update binaries"
          file_pattern: 'ota/* ota/master/* ota/beta/* webflash/*'
          branch: binary
          skip_dirty_check: true
          skip_fetch: true
          skip_checkout: true
          disable_globbing: true
          add_options: '-f'
          push_options: '-f'
