name: standalone

on:
  workflow_dispatch:
  release:
    types: [ published ]
  pull_request:
    branches: [master]
    paths:
      - 'scripts/build-standalone.sh'
      - 'scripts/standalone.json'

jobs:
  configure:
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.fetch.outputs.matrix }}
    steps:
     - name: Checkout to repository
       uses: actions/checkout@v4
     - name: fetch matrix data
       id: fetch
       run: echo "matrix=$(jq -c . < scripts/standalone.json)" >> $GITHUB_OUTPUT
  build:
    runs-on: ubuntu-latest
    needs: configure
    strategy:
      fail-fast: false
      matrix: ${{ fromJson(needs.configure.outputs.matrix) }}
    env:
      WORKSPACE: "/opt"
    steps:
      - name: checkout
        uses: actions/checkout@v4
      - name: Install UPX
        uses: crazy-max/ghaction-upx@v3
        with:
          install-only: true
      - name: cache
        uses: actions/cache@v4
        with:
          path: ${{ env.WORKSPACE }}/toolchains
          key: ${{ matrix.os }}-${{ matrix.arch }}-${{ hashFiles('scripts/build-standalone.sh') }}
      - name: Cross compile
        run: |
          ./scripts/build-standalone.sh
        env:
          CANDY_WORKSPACE: ${{ env.WORKSPACE }}
          CANDY_OS: ${{ matrix.os }}
          CANDY_ARCH: ${{ matrix.arch }}
          CANDY_STRIP: "0"
          CANDY_UPX: "0"
          CANDY_TGZ: "1"
      - name: upload
        uses: actions/upload-artifact@v4
        with:
          name: candy-${{ matrix.os }}-${{ matrix.arch }}
          path: ${{ env.WORKSPACE }}/output/${{ matrix.os }}-${{ matrix.arch }}
      - name: prepare package
        shell: bash
        if: github.event_name == 'release'
        run: |
          GIT_TAG=${{ github.event.release.tag_name }}
          PKG_PATH=${{ env.WORKSPACE }}/output/candy_${GIT_TAG#v}+${{ matrix.os }}_${{ matrix.arch }}.tar.gz
          mv ${{ env.WORKSPACE }}/output/candy-${{ matrix.os }}-${{ matrix.arch }}.tar.gz $PKG_PATH
          echo "PKG_PATH=$PKG_PATH" >> $GITHUB_ENV
      - name: release
        uses: softprops/action-gh-release@v2
        if: github.event_name == 'release'
        with:
          files: ${{ env.PKG_PATH }}
