# This updates the Web Installer with the files from the webinstaller folder and the binary of the latest release
# it only gets run on:
#  - Manually triggered
# Make sure to also update the lower part of build.yml!

name: Manual Web Installer Update

on:
  workflow_dispatch: # Run on manual trigger
#  push:
#    branches:
#    - rolling
#    paths:
#    - webinstaller # The path filter somehow does not work, so lets run it on every change to rolling

jobs:
  manually-update-web-installer:    
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest

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

    steps:
    - name: Checkout
      uses: actions/checkout@v3
      
    - name: Get version of last release
      id: last_release
      uses: joutvhu/get-release@v1
      with:
        latest: true
        prerelease: false
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

    - name: Add binary to Web Installer and update manifest
      run: |
        echo "Updating Web installer to use firmware from ${{ steps.last_release.outputs.tag_name }}..."
        rm -f webinstaller/binary/firmware.bin
        wget ${{ github.server_url }}/${{ github.repository }}/releases/download/${{ steps.last_release.outputs.tag_name }}/AI-on-the-edge-device__update__${{ steps.last_release.outputs.tag_name }}.zip
        unzip AI-on-the-edge-device__update__${{ steps.last_release.outputs.tag_name }}.zip
        cp -f firmware.bin webinstaller/binary/firmware.bin
        echo "Updating index and manifest file..."
        sed -i 's/$VERSION/${{ steps.last_release.outputs.tag_name }}/g' webinstaller/index.html
        sed -i 's/$VERSION/${{ steps.last_release.outputs.tag_name }}/g' webinstaller/manifest.json

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

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

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