name: BTClock WebUI CI

on: [push]

env:
  PUBLIC_BASE_URL: ""

jobs:
  check-changes:
    runs-on: ubuntu-latest
    outputs:
      all_changed_and_modified_files_count: ${{ steps.changed-files.outputs.all_changed_and_modified_files_count }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: Get changed files count
        id: changed-files
        uses: tj-actions/changed-files@v40.1.1
        with:
          files_ignore: "doc/**,README.md,Dockerfile,.*,.github/**"
          files_ignore_separator: ','
      - name: Print changed files count
        run: >
          echo "Changed files count: ${{ 
            steps.changed-files.outputs.all_changed_and_modified_files_count }}"

  build:
    needs: check-changes
    runs-on: ubuntu-latest
    if: ${{ needs.check-changes.outputs >= 1 }}
    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v3
        with:
          submodules: recursive
      - uses: actions/setup-node@v3
        with:
          node-version: lts/*
          cache: yarn
          cache-dependency-path: '**/yarn.lock'
      - uses: actions/cache@v3
        with:
          path: |
            ~/.cache/pip
            ~/node_modules
          key: ${{ runner.os }}-pio
      - uses: actions/setup-python@v4
        with:
          python-version: '3.9'
      - name: Get current date
        id: dateAndTime
        run: echo "dateAndTime=$(date +'%Y-%m-%d-%H:%M')" >> $GITHUB_OUTPUT
      - name: Install mklittlefs
        run: >
          git clone https://github.com/earlephilhower/mklittlefs.git /tmp/mklittlefs &&
          cd /tmp/mklittlefs &&
          git submodule update --init &&
          make dist
      - name: Install yarn
        run: yarn && yarn postinstall
      - name: Build WebUI
        run: yarn build
      - name: Get current block
        id: getBlockHeight
        run: echo "blockHeight=$(curl -s https://mempool.space/api/blocks/tip/height)" >> $GITHUB_OUTPUT
      - name: gzip build for LittleFS
        run: find dist -type f ! -name ".*" -exec sh -c 'mkdir -p "build_gz/$(dirname "${1#dist/}")" && gzip -k "$1" -c > "build_gz/${1#dist/}".gz' _ {} \;
      - name: Create tarball
        run: tar czf webui.tgz --strip-components=1 dist
      - name: Build LittleFS
        run: /tmp/mklittlefs/mklittlefs -c build_gz -s 409600 littlefs.bin 
      - name: Upload artifacts
        uses: actions/upload-artifact@v3
        with:
          path: |
            webui.tgz
            littlefs.bin
      - name: Create release
        uses: ncipollo/release-action@v1
        with:
          tag: ${{ steps.getBlockHeight.outputs.blockHeight }}
          commit: main
          name: release-${{ steps.getBlockHeight.outputs.blockHeight }}
          artifacts: "littlefs.bin,webui.tgz"
          allowUpdates: true
          removeArtifacts: true
          makeLatest: true