name: Compile
permissions:
  contents: write
on:
  push:
    branches: [ main ]
    paths:
      - 'src/**'
      - 'lib/**'

jobs:
  compile_firmware:
    name: Compile the firmware
    runs-on: ubuntu-latest
    steps:
      - name: Check out the repository
        uses: actions/checkout@v3
        
      - name: Cache pip
        uses: actions/cache@v2
        with:
          path: ~/.cache/pip
          key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
          restore-keys: |
            ${{ runner.os }}-pip-

      - name: Cache PlatformIO
        uses: actions/cache@v2
        with:
          path: ~/.platformio
          key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}

      - name: Set up Python
        uses: actions/setup-python@v2

      - name: Install PlatformIO
        run: |
          python -m pip install --upgrade pip
          pip install --upgrade platformio

      - name: Install jo
        run: sudo apt-get -y install jq

      - name: Extract version number
        id: version_number
        run: |
          echo "::set-output name=firmware_version::$(grep '*VERSION' src/Globals.cpp | cut -d'=' -f2 | sed -r 's/"(.*)";/\1/' | awk '{$1=$1};1')"

      - name: Create Versionfile  
        run: echo '${{ steps.version_number.outputs.firmware_version }}' > version

      - name: Run PlatformIO
        run: pio run --environment ulanzi

      - name: Copy firmware to output directory
        run: cp .pio/build/ulanzi/firmware.bin docs/flasher/firmware

      - name: Create new manifest.json
        run: cat docs/flasher/firmware/manifest.json | jq '.version="${{ steps.version_number.outputs.firmware_version }}"' > docs/flasher/firmware/new-manifest.json
      
      - name: Override previous manifest.json
        run: mv docs/flasher/firmware/new-manifest.json docs/flasher/firmware/manifest.json

      - name: Upload firmware as artifact
        uses: actions/upload-artifact@v2
        with:
          name: firmware
          path: .pio/build/ulanzi/firmware.bin

      - name: Create Release
        id: create_release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ steps.version_number.outputs.firmware_version }}
          release_name: Release ${{ steps.version_number.outputs.firmware_version }}
          draft: false
          prerelease: false

      - name: Upload Release Asset
        id: upload-release-asset
        uses: actions/upload-release-asset@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          upload_url: ${{ steps.create_release.outputs.upload_url }}
          asset_path: .pio/build/ulanzi/firmware.bin
          asset_name: firmware.bin
          asset_content_type: application/octet-stream

      - name: Commit
        id: commit   
        uses: stefanzweifel/git-auto-commit-action@v4
